【问题标题】:Possible to used an int scanner with a string? [duplicate]可以使用带字符串的 int 扫描仪吗? [复制]
【发布时间】:2015-11-11 15:02:44
【问题描述】:

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

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

但是您将如何执行此操作,因为我希望在 while 语句中执行此操作,并使用它来终止语句。

【问题讨论】:

  • 您可以接受字符串并将其解析为整数。
  • 扫描器永远不会与数据类型相关联。您可以从扫描仪读取几乎任何类型。您可以将所有内容读取为字符串并将它们解析为整数
  • 正如@Phantomazi 所说,您可以接受字符串并将它们解析为整数,int input = Integer.parseInt("string from scanner")
  • 如果Integer#parseInt 失败,请确保处理NumberFormatException
  • 首先检查字符串是否等于"done" 或使用matches("\\d+") 进行检查,然后将它们解析为整数。这将防止 known NumberFormatExceptions.

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


【解决方案1】:

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

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
           }
        }
    }
}

【讨论】:

  • 请注意,您不需要continueReading,因为您有break。你可以做while (true)
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2023-04-10
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
相关资源
最近更新 更多