【发布时间】:2015-05-08 05:19:34
【问题描述】:
好的,我在字符中使用 switch 语句,如果用户将位置键入为“r”,则会出现消息并告诉他们选择正确的位置。一切正常,但是我希望代码不允许用户保存不正确的位置,直到输入正确的位置。
有人能读一下这段代码,也许可以告诉我它是如何完成的,谢谢。
public Property(String theAddress, int theBedrooms, char theLocation)
{
address = theAddress;
bedrooms = theBedrooms;
location = theLocation;
switch(theLocation){
case 'n': theLocation = 'N';
case 'N': theLocation = 'N';
break;
case 'e': theLocation = 'E';
case 'E': theLocation = 'E';
break;
case 's': theLocation = 'S';
case 'S': theLocation = 'S';
break;
case 'w': theLocation = 'W';
case 'W': theLocation = 'W';
break;
default: theLocation = '0';
System.out.println("###########################");
System.out.println("# Enter Correct Location #");
System.out.println("# North London = N #");
System.out.println("# East London = E #");
System.out.println("# South London = S #");
System.out.println("# West London = W #");
System.out.println("###########################");
}
}
【问题讨论】:
-
传统上,您使用的循环在输入正确的输入之前不会退出。
-
使用
while(! isCorrectOne(myString)){myString =scanner.next()}将其用于您所需的数据类型.. -
验证用户输入是一个在很多地方都被广泛和反复讨论过的话题。请进行尽职调查,并在询问之前先自己进行研究和尝试。
-
在对象构造函数中验证用户输入不是一个好主意,在用户输入值时验证它,如果仍然传递了错误值,则在构造函数中抛出异常,只是可以肯定。
-
将 SO 用于标准帖子....首先尝试一些东西,如果遇到问题,敲门 SO .. :)