2013-10-28 132 views
1

对于一个学校任务,我必须制作一个程序,从终端读取两个数字,然后处理这些数字。程序输入后必须自动处理这两个值。我目前使用的代码在下面,但是在程序乘以数字之前必须先按下Enter键,用户不必按下输入三次,而只需按两次。Java 2行终端输入

public static void man(String[] args) throws NumberFormatException, IOException{ 
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
    int count = 0; 
    int width = 0; 
    int height= 0; 
    String number; 
    while((number = reader.readLine())!=null && count < 2) { 
     while(count < 2){ 
      if(count == 0) { 
       width = Integer.parseInt(number); 
       count++; 
       break; 
      } 
      else if (count == 1) { 
       height = Integer.parseInt(number); 
       count++; 
       break; 
      } 
     } 
    } 
    System.out.println(width * height); 
} 

这是用户如何具有使用该程序的那一刻

  1. 输入数字1,然后按回车
  2. 输入数字2,然后按回车
  3. 输入任何内容,然后按回车
  4. 程序打印相乘的数字

但是,这是用户应该如何使用该程序的那一刻:

  1. 输入数字1,然后按回车
  2. 输入数字2,然后按回车
  3. 程序打印多倍数字

当然,我的程序必须为作业做些不同的事情,但我已经改变了一点,以便在这里更容易解释。

谢谢您提前帮忙!

+0

您的主要方法的名称为“man”。请纠正它。 – Christian

回答

0

试试这个修改:

public static void main(String[] args) throws NumberFormatException, 
     IOException { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(
      System.in)); 
    int count = 0; 
    int width = 0; 
    int height = 0; 
    String number; 
    while (count < 2) { // Just 2 inputs 
     number = reader.readLine(); 
     if (count == 0) { 
      width = Integer.parseInt(number); 
      count++; 
     } else if (count == 1) { 
      height = Integer.parseInt(number); 
      count++; 
     } 
     else // If count >= 2, exits while loop 
      break; 
    } 
    System.out.println(width * height); 
} 
+0

你的方法很容易理解,所以我打算用你的方法,但亚伦的方法也起作用。感谢您快速回答! – user2929285

0

这样计算< 2在readLine()之前检查,否则它会在检查计数之前尝试读取一个数字。

即那些检查从左向右计算

+0

谢谢!这工作得很好,但Christian的方法更容易理解,所以我将使用那个。非常感谢您的快速回答! – user2929285

0

使用java.util.Scanner中的类用户输入

Scanner scanner = new Scanner(System.in); 
int width = scanner.nextInt(); 
int height = scanner.nextInt(); 
scanner.close(); 
System.out.println(width * height); 
1

既然你做了学校的任务,我会提出另一个建议:消除令人困惑的任务条件。我知道你已经看到了这个地方,并会继续在很多地方看到它,甚至会遇到那些热情地提倡它的人,但我认为它往往会混淆事物。如何:

for (int i=0; i<2; i++) 
{ 
    String number = reader.readLine(); 
    if (i == 0) { height = Integer.parseInt(number); } 
     else { width = Integer.parseInt(number); } 
}