根据用户输入使程序退出



当我输入"Q";或";q〃;。然而,循环永远不会结束。你能帮我弄清楚吗?

public static void main(String[] args) {
Scanner input= new Scanner(System.in);
char str ;

do {
System.out.println("Choose one of the following option : ");
System.out.println("U or u - to convert SAR amount to USD");
System.out.println("E or e - to convert SAR amount to EURO");
System.out.println("Q or q - to quit");
str = input.next().charAt(0);

if (str == 'U' || str == 'u'  ) {

}
else if (str == 'E' || str == 'e'  ){

}   
} while( str != 'Q' || str != 'q' );
}

str != 'Q' || str != 'q'始终为true。任何给定的字符串都不等于其中的一个或另一个(或两者(。您需要&&而不是||

一个很好的结构是类似于C中为getopt_long((推荐的结构,但显然是为Java推荐的结构。可以在此处阅读手册页https://linux.die.net/man/3/getopt_long

while(true)
{
str = input.next().charAt(0);      

if(str.toUpperString.equals('Q'))
{
break;
}
// In general if you want upper and lower case to do the same thing 
//use toUpperString
switch (str) {
case 'U': 
case 'u':
// Do something
break;

case 'E':
case 'e':
// Do something
break;
default:
System.out.println("Wrong input");    
break;
}
}

如果您不想使用switch语句,这个问题的另一个好的解决方案是loop半。https://codehs.gitbooks.io/introcs/content/Basic-JavaScript-and-Graphics/loop-and-a-half.html

结构如下:

while(true)
{
String token = Character.toUpperCase( input.next().charAt(0) );
if(token.equals('A'))
{
// Do something
}
else if(token.equals('B'))
{
// Do something
}
else if(token.equals('Q'))
{
break;
}
else
{
System.out.println("Invalid Option");
}
}

如果您想在编写Q或Q时停止程序,您可以将输入转换为小写或大写中的任何一种。

str.toUpperCase();
if (str == 'U'){
}
else if (str == 'E'){
}   

} while( str != 'Q');
}

更改检查Q或Q的条件。

while( str != 'Q' && str != 'q' );

对于上面的代码片段,如果str不是Q或Q,则执行while循环。

public static void main(String [] args) {
Scanner input= new Scanner(System.in); 
char str ;
do{
System.out.println("Choose one of the following option : ");
System.out.println("U or u - to convert SAR amount to USD");
System.out.println("E or e - to convert SAR amount to EURO");
System.out.println("Q or q - to quit");
str = input.next().charAt(0);

if (str == 'U' || str == 'u'){}
else if (str == 'E' || str == 'e'){}   

} while(str != 'Q' && str != 'q');  // change the condition from || to &&
// Also close the input stream to avoided memery leakage 
input.close();
}

最新更新