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