所以我正在为我的Java类创建简单的程序,最后一个要求是让程序循环。我之前已经这样做了,但它非常低效且令人费解。
基本上,我使用了一个名为start的switch case,其值为0和1.如果用户键入0,则do-while循环将开始,如果他们键入1,则程序将终止。唯一的问题是用户必须输入0才能使程序开始,如果他们键入1,我必须有一个故障保护,将start的值更改为3,否则将开始无限循环。有人可以帮我找到更好的方法吗? (此外,在任何人说出它的编写方式之前,其中一个要求是它必须在一个可执行类中完成。) (另外,还有人可以告诉我压痕的规则吗?我真的太可怕了。)
以下是我的代码:
/*
* Simple Java Survey Program
*/
import java.util.Scanner;
public class J2Strings {
public static void main(String[] args) {
// TODO Auto-generated method stub
// variables
String fName;
String lName;
String mName;
int age;
String say;
String fFood;
String fTV;
Scanner userInput = new Scanner(System.in);
System.out.println("Today you are going to take a small personal survey");
System.out.println("");
System.out.println("Begin by entering your first name: ");
fName = userInput.next();
System.out.println("Enter your last name:");
lName = userInput.next();
System.out.println("Enter your middle name:");
mName = userInput.next();
System.out.println("Enter your age:");
age = userInput.nextInt();
System.out.println("Enter your favorite saying:");
say = userInput.next();
System.out.println("Enter your favorite food:");
fFood = userInput.next();
System.out.println("Finally, enter your favorite TV show:");
fTV = userInput.next();
char f = fName.charAt(0);
char l = lName.charAt(0);
char m = mName.charAt(0);
System.out.println("Based on the information you entered, here are your initials: " + f + "." + m + "." + l);
System.out.println("This is how old you will be in 50 years: " + (age + 50));
}
}
答案 0 :(得分:1)
像这样的东西
bool test = true;
while(test)
{
/*Your code here */
/*At the end you ask them if they want to try again*/
/*Then switch the boolean based on their answer*/
}