如何获取用户的输入并将其用作整数?

时间:2014-11-07 16:31:25

标签: java

我是两天前刚安装Eclipse的新用户。我正在编写一个程序,向用户询问他们在百分比形式上获得的成绩,并以字母形式返回他们的成绩。我也想知道如何在if-else语句中设置这个整数,所以如果测试等级大于或等于90,程序将返回A作为等级。所以依此类推,直到50或更低,这将返回F.到目前为止,我只有这个:

import java.util.Scanner;

public class gradechecker {

    public static void main(String[]args) {

        Scanner user_input = new Scanner(System.in);

        String test_grade;
        System.out.println("Enter the grade percentage you received without the percent sign.");
        test_grade = user_input.next();


        if(test_grade <= 90) {

        }
    }
}

3 个答案:

答案 0 :(得分:2)

要从用户获取整数值,请使用.nextInt()。 在这种情况下,

test_grade = user_input.nextInt();

test_grade获取用户输入的值。 但是,test_grade被声明为String 变量。您需要将其更改为int。

答案 1 :(得分:1)

对于问题的一部分,August和azurefrog所说的是正确的,您希望使用user_input.nextInt()代替user_input.next()来获取用户的int输入。

对于问题的第二部分,请考虑检查输入以及如何检查输入的最佳顺序。

我会考虑改用>=。首先检查A,然后检查B等。如果某些事情>≥80但你已经确定它不是&gt; = 90,那么你知道它将是一个B.记得检查用户是否输入了无效的号码。请记住使用if...else if...else逻辑加入比较,否则可能会导致错误的结果。

编辑:正如所指出的,test_grade需要是一个int而不是一个String。

答案 2 :(得分:0)

 public static void main(String[]args) {

        Scanner user_input = new Scanner(System.in);

You must use int to get the percentage in integer form
        int test_grade;
        System.out.println("Enter the grade percentage you received without the percent sign.");

获取输入使用input.nextInt ...检查http://www.java-made-easy.com/java-scanner.html

    test_grade = user_input.nextInt();

//Check for the conditions similar to this
            if(test_grade >= 90) {
    // assign the grade here
    String grade = A;
    // print the grade 
    System.out.println("your grade is"+grade)

            }