验证:确保字符串是一个数字

时间:2015-04-10 14:32:36

标签: java string validation double try-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'
              }

   }

我有一张它的作品图片,见下文。我写的字数是它输出的次数'开始时间必须是数字'!

1 个答案:

答案 0 :(得分:0)

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

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");
    }
}