好的,所以我试图改变一些事情。
所以我已经将我的扫描仪转换为字符串,现在我想要做的是,获取它们输入的值并将其用作其他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.....");
}
}
答案 0 :(得分:4)
您应该在parseInt
中使用参数:
int num2 = Integer.parseInt(num1);
和
if (num2 >= 275)
...
答案 1 :(得分:2)
试试这个:
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的字符,你需要更好地捕获它,但要记住它
答案 2 :(得分:0)
您也可以使用其他类型的扫描仪方法来获取int值
num = number.nextInt();
答案 3 :(得分:0)
这是我所做的:
Scanner input = new Scanner(System.in);
System.out.println("Type number");
int number = input.nextInt();
System.out.println(number);
希望这对您有帮助...
答案 4 :(得分:-1)
我自己并不是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.....");
}
}
}