我想在Java中編寫一個接受某些用戶輸入並將其傳遞給某些方法的主要方法。如何讓Java接受某些用戶輸入並將信息傳遞給某些方法?
到目前爲止我的代碼:
//this method prints a menu to the console
public static void menu(){
System.out.println("Select one of the following:\n");
System.out.println("Enter Observatory Data[1]");
System.out.println("Enter Earthquake Data[2]");
System.out.println("Get Largest Ever Earthquake[3]");
System.out.println("Get All Earthquakes Greater Than X[4]");
System.out.println("Exit[5]");
}
public static void main(String[] args){
Scanner reader= new Scanner(System.in);
menu(); //print the menu to screen
String input1=reader.next(); //user should select 1,2,3,4 or 5
boolean cheese=false; //keep the program running
while (cheese=false){
if (input1.matches("[a-zA-Z67890]*")){ //if anything but 1,2,3,4,or 5 is entered return this string and reprint the menu
//int inputNum1=Integer.parseInt(input1);
System.out.println("no work!");
menu();
String input2=reader.next();
}else if(input1.matches("1")){ //if user types 1 accept some information and pass it to the Observatory method
System.out.println("What is the Observatory name?");
String observatoryName = reader.next();
System.out.println("What country is the observatory in?");
String country = reader.next();
System.out.println("What year did the observatory open??");
String year = reader.next();
System.out.println("Observatory added. Waht next?");
System.out.println("What area does the observatory cover?");
String area = reader.next();
Observatory newObservatory = new Observatory(observatoryName,country,Integer.parseInt(year),Double.parseDouble(area));
也有一些其他的選擇,但只有一個粘貼在這裏應該足夠了。當前代碼運行,打印菜單並接受一些用戶輸入,但只要程序終止,儘管boolean cheese
仍然爲false
。有沒有人建議我如何才能運行Java,直到鍵入選項5並在選擇1時檢索某些信息?
,而(奶酪= false)應該是while(cheese == false) – ergonaut
不是真的回答你的問題,但它可能更容易使用switch語句,而不是使用一堆「if/else」,我覺得像默認情況下可能非常有用。 – Austin
實際上,它應該是'while(!cheese)' –