2

好的,所以我正在尝试转换一些东西。

所以我已经将我的扫描仪转换为字符串,现在我想做的是,获取他们输入的值并将其用作几个 else 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.....");
}

}

4

5 回答 5

5

你应该使用一个参数parseInt

int num2 = Integer.parseInt(num1);

if (num2 >= 275) 
...
于 2012-08-29T23:10:44.223 回答
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 的字符,你需要比这更好地捕捉它,但请记住这一点

于 2012-08-29T23:13:47.613 回答
0

您也可以使用其他类型的扫描仪方法来获取 int 值

num = number.nextInt();
于 2012-08-30T11:57:09.963 回答
0

这是我所做的:

Scanner input = new Scanner(System.in);
System.out.println("Type number");
int number = input.nextInt();
System.out.println(number);

希望这可以帮助...

于 2018-07-19T04:05:04.757 回答
-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.....");
    }
}
}
于 2015-08-27T16:09:54.147 回答