好的,我正在尝试转换一些东西。
所以我已经将我的Scanner转换为String,现在我想做的是,取他们输入的值,并将其用作其他if语句的整数。这行不通!
这是我到目前为止的代码:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner fname = new Scanner(System.in);
Scanner sname = new Scanner(System.in);
Scanner number = new Scanner(System.in);
tuna weight = new tuna();
System.out.println("Enter Your First Name: ");
String fname1 = fname.nextLine();
String fnames = fname1;
System.out.println("Enter Your Last Name: ");
String sname1 = sname.nextLine();
String snames = sname1;
System.out.println("Enter Your Weight (Lbs.) : ");
String num = number.nextLine();
String num1 = num;
System.out.println("Okay " + fname1 + " " + sname1
+ " I can see here that you weigh " + num + "lbs.");
int num2 = num1.parseInt();
if (num1 >= 275)
System.out
.println("You know, you should maybe consider laying off the candy my friend.....");
}
}
您应该在parseInt
:中使用参数
int num2 = Integer.parseInt(num1);
和
if (num2 >= 275)
...
试试这个:
try{
num2 = Integer.parseInt(num1);
}
catch(Exception ex) {
System.out.println("Something went wrong, the string could not be converted to int.");
}
try-catch非常重要,因为字符串可能包含无法转换为int的字符,因此您需要更好地捕获它,但请记住
您也可以使用其他类型的scanner方法来获取int值
num = number.nextInt();
以下是我所做的:
Scanner input = new Scanner(System.in);
System.out.println("Type number");
int number = input.nextInt();
System.out.println(number);
希望这能帮助。。。
我自己不是Java专业人士,但我对您的代码进行了更高的调整以使其正常工作。给你。很高兴能帮上忙。
p
ackage APPLE;
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner fname = new Scanner(System.in);
Scanner sname = new Scanner(System.in);
Scanner number = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
System.out.println("Enter Your First Name: ");
String fname1 = fname.nextLine();
String fnames = fname1;
System.out.println("Enter Your Last Name: ");
String sname1 = sname.nextLine();
String snames = sname1;
System.out.println("Enter Your Weight (Lbs.) : ");
int num = intScanner.nextInt();
System.out.println("Okay " + " " + fname1 + " " + sname1
+ " I can see here that you weigh " + num + "lbs.");
if (num > 275){
System.out.println("You know, you should maybe consider laying off the candy my friend.....");
}
}
}