Java 2行终端输入

时间:2013-10-28 18:55:12

标签: java terminal system.in

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

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并按Enter
  2. 输入数字2并按Enter键
  3. 不输入任何内容并按Enter键
  4. 程序打印相乘的数字
  5. 但目前用户应该如何使用该程序:

    1. 输入数字1并按Enter
    2. 输入数字2并按Enter键
    3. 程序打印相乘的数字
    4. 当然我的程序必须为作业做一些不同的事情,但我已经改变了一点,以便在这里更容易解释。

      提前感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

由于你正在完成学校作业,我会提出另一个建议:消除条件中混乱的分配。我知道你已经在某个地方看过这个,并且会继续在很多地方看到它,甚至会遇到热情地提倡它的人,但我认为这往往会让事情变得混乱。怎么样:

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

答案 1 :(得分:0)

是否计算&lt; 2在readLine()之前检查,否则它会在检查计数之前尝试读取一个数字。

即那些支票从左到右评估

答案 2 :(得分: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);
}

答案 3 :(得分: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 ); 
相关问题