2015-11-02 16 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. 
} 
相关问题