【问题标题】:how to retrieve a line of input of different primitive types如何检索不同原始类型的输入行
【发布时间】:2017-04-14 12:58:40
【问题描述】:

首先我创建了一个布尔值,然后将其设置为 true 以启用第一次运行...然后后续运行将基于用户输入。

    boolean emptyLine = true;
          String name; int quantity; double price; 

Scanner scan = new Scanner(System.in);

      while(emptyLine != false) //repeatedly request user input if input is not empty
      { 
         //ask the user for the quantity of items being purchased.
         System.out.println("Enter name of item: Enter quantity of item purchased: Enter price of item being purchased: ");
         input = scan.nextLine();  //should read the line of input

         item =                         //name of item from the line of input.
         quantity = scan.nextInt();     //should get the quantity from the line of input
         price = scan.nextDouble();     //get the price from the line of input

         if(input.length() >= 0)
         {
            emptyLine = true;
         }
         else
         {
            emptyLine = false;
         }

      }

我正在尝试编写代码来检查用户输入是否为空。这样,如果用户输入为空,则要求用户输入有效的输入或退出。

例如,如果用户输入一个空格,我希望我的程序接受它,但如果用户按下 ENTER 按钮,那么它应该被拒绝。

【问题讨论】:

  • item = quantity = scan.nextInt() 是故意的吗? PS:input.length() >= 0 给你你想要的布尔值,不需要 if-else
  • 由于您将整行读入input,您应该解析该字符串,例如通过使用分词器、正则表达式等。
  • 你真的应该看看Scanner#hasNextLine()。此外,您可能最终会遇到this 问题
  • 您确定不应该检查您阅读的 每个 项目的输入吗?
  • @TimBiegeleisen 如果我正在检查每个项目输入,那么我的程序将是重复的......但我意识到我可以使用一行请求所有输入,然后从输入行中提取我的数据。我只是不知道如何编码。

标签: java string boolean


【解决方案1】:

一种简单的方法:

while (scann.hasNextLine()) {
  String userInput = scan.nextLine();

现在 userInput 是一个字符串;您可以手动检查其内容;例如通过调用 isEmpty();如果不为空,则可以尝试转换为下一个预期的类型。

【讨论】:

  • 你是什么意思:“不起作用”。当您希望其他人帮助您时,该问题描述“不起作用”...
  • 使用 scan.hasNextLine();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
相关资源
最近更新 更多