【问题标题】:Validation: to make sure the string is a number验证:确保字符串是数字
【发布时间】:2015-04-10 14:32:35
【问题描述】:

我正在为我的课程作业编写代码,我需要验证方面的帮助。我想确保输入的字符串是一个数字。 我的老师给了我一段代码,用 try and catch,它确实有效,但它有一个我不知道如何解决的问题。

因此,如果有人可以通过告诉我此代码有什么问题来帮助我,我将不胜感激,或者如果有人可以给我另一个简单的代码来验证数据以确保它是一个数字。

boolean StartTimeIsANumber; // BOOLEAN CREATED
  StartTimeIsANumber = false; // BOOLEAN SET TO FALSE
  double starttime=0; // VARIBALE IS INITIALISED

  System.out.println("Please enter the start time in seconds"); // asks for time in seconds

  while(StartTimeIsANumber==false) // WHILE OK IS FALSE
   {
    try {

     String input; // start time is stored as a string
     input = kb.next(); // reads the start time in as a string
     starttime = Double.parseDouble(input); // converts to double
     System.out.println("start time: "+starttime); // outputs the start time
     StartTimeIsANumber =true; // if its a number boolean set will convert to true and will break out of the loop
     }  catch (NumberFormatException e) {
      // TODO Auto-generated catch block
      // e.printStackTrace(); (this is the line that makes red writing, commenting it out stops red writing)
      System.out.println("start time must be a number"); // further 'advice'
              }

   }

我有一张它的作用的图片,见下文。我写的字数就是它输出'start time must be a number'的次数!

【问题讨论】:

  • 您的catch 块在尝试解析不是双值StringString 时捕获parseDouble 方法抛出的Exception。这看起来不错。
  • 您是否尝试过在22 表格中输入数字而不是twenty two
  • 哇,这是你从老师那里得到的资料?你需要更换你的老师。 :-(
  • kb 是如何声明和初始化的?
  • @rav,它工作正常。没有人告诉你它应该只返回一个这样的回复。它会检查您输入的每个单词是否为数字,因为您可能会输入“oops 22.5”之类的内容,因此它会在22.5 中成功。

标签: java string validation double try-catch


【解决方案1】:

它会迭代该行的每个单词。您必须将整个输入行视为一个语句。

boolean StartTimeIsANumber = false; 
double starttime=0; // VARIBALE IS INITIALISED
String input = "";

System.out.println("Please enter the start time in seconds");

while(StartTimeIsANumber == false) {
    try {
        while (kb.hasNext()) {
            input += (kb.next() + " ");  
        }
        // or input = kb.nextLine();

        starttime = Double.parseDouble(input);
        System.out.println("start time: " + starttime);
        StartTimeIsANumber = true;
    }  catch (NumberFormatException e) {
        System.out.println("start time must be a number");
    }
}

【讨论】:

  • 使用kb.nextLine(); 调用清除其余行可能更简单。
  • 你能评论一下你添加的位吗,因为我只有 14 岁,不知道他们做什么?如果可以的话,会很有帮助!不过感谢您的帮助! :D @jvDx
猜你喜欢
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
相关资源
最近更新 更多