2015-11-02 17 views
0

我想在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時檢索某些信息?

+2

,而(奶酪= false)應該是while(cheese == false) – ergonaut

+0

不是真的回答你的問題,但它可能更容易使用switch語句,而不是使用一堆「if/else」,我覺得像默認情況下可能非常有用。 – Austin

+0

實際上,它應該是'while(!cheese)' –

回答

4

在您的while循環條件下,您將奶酪設置爲假而不是將奶酪與假點比較。將其更改爲

while(!cheese) { 

您也可以等待更多的用戶輸入您上次實際輸入後。因此,該程序退出前等待進一步的用戶輸入

reader.next(); 

:所以你最後一行之後,添加此。如果我正確理解你的程序,你可以做到這一點,刪除while循環,並達到預期的效果。

+0

沒有看到更多他們的代碼,我不能投票表示你已經回答了這個問題。 –

+0

當然啊。我和我的Matlab方法讓我失望。感謝你們! – CiaranWelsh

1

你而條件是不正確...... 它應該是:

boolean cheese = true; 
while (cheese) 
{ 
    // Do stuff. 
} 

,或者如果你真的想你的奶酪布爾是假的,只是這樣做:

boolean cheese = false; 
while (!cheese) 
{ 
    // Do stuff. 
} 
相關問題