我正在尝试将其转换为Java程序:
$ java SpaceTravel
Welcome to the SpaceTravel agency
What do you want do? [h for help]
a
Unknown command. Type h for help
What do you want do? [h for help]
h
h: print this help screen
q: quit the program
What do you want do? [h for help]
q
Bye bye!
现在我的程序似乎在第二个do while
循环中执行了无限循环的问题,无论我选择了什么,我都尝试了许多算法,而钢将无法为我工作。这是我的代码:
package gesitionEleve;
import java.util.Scanner;
public class SpaceTravel {
public static void main(String[] args) {
System.out.print("Welcom to the SpaceTravel Agency\n");
int lafin = 0;
while (lafin != 1) {
int taill;
do {
System.out.print("What do you want to do [h for help] : ");
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
taill = test.length();
} while(taill == 0);
char choix = 0;
String test;
if (choix != 'h') {
do {
System.out.print("\nUknown command. Type h for help ");
System.out.print("\nWhat do you want to do : ");
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
} while(choix == 'h');
}
System.out.print("\nh : print this help page ");
System.out.print("\nq : quite the program ");
do {
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
switch(choix) {
case 'h' :
System.out.print("\nh : print this help page ");
System.out.print("\nq : quite the program ");
case 'q' :
System.out.print("Bye bye");
lafin++;
}
} while (choix == 'q' || choix == 'h');
}
}
}
以下程序适合您的需求:
import java.util.Scanner;
public class SpaceTravel
{
public static void main(String[] args) {
System.out.print("Welcome to the SpaceTravel Agency\n");
String str; //To avoid exception when user enters just an enter
while (true) { //infinite loop
char choix; //for getting a character
System.out.print("What do you want to do [h for help] : ");
Scanner sc = new Scanner(System.in);
str=sc.nextLine(); //get input
if(str.length()!=1) //If no characters or more than one character is entered,
{
System.out.println("Invalid Choice");
continue;
}
choix=str.charAt(0); //get char from str
if(choix=='q') //if char is q,break out of the while loop
break;
if (choix != 'h') { //if char is not h,print invalid input and continue the loop
System.out.println("\nUnknown command. Type h for help ");
continue;
}
System.out.print("\nh : print this help page ");
System.out.print("\nq : quit the program ");
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句