可以使用带有字符串的int扫描程序吗?

时间:2015-11-11 15:02:45

标签: java string input integer java.util.scanner

我知道这个问题听起来有点夸夸其谈但我很好奇是否可以在整数扫描仪中使用字符串。

我问这个是因为我很好奇,例如,如果用户在输入了他们想要的所有数字后输入数字和类型DONE。我知道我可以做到这一点,我会让他们进入例如。小于0的数字(这可能适用于成绩)。

但是你如何做这个,因为我希望在while语句中做,并用它来终止语句。

1 个答案:

答案 0 :(得分:0)

如评论中所述,扫描仪与数据类型无关。话虽如此,这可能是一个简单的解决方案 - 请记住,可以改进它以更好地处理您的异常!

import java.util.Scanner;                               

public class Start {

public static void main(String[] args) {
    Scanner Reader = new Scanner(System.in);    
    boolean continueReading = true;
    int grade;
    while (continueReading)
    {
        String input;                                      
        System.out.println("Please input a number or type in Done to exit.");

        input = Reader.nextLine();                       
        if(input.equalsIgnoreCase("Done"){
           System.out.println("Finishing..");
           continueReading == false;
        }
        else{
           try{
              grade = Integer.parseInt(input);
              System.out.println("The grade is: " + grade);
           }catch(NumberFormatException e){
              //Some exception handling
           }
        }
    }
}