1

学校の課題のために、端末から 2 つの数字を読み取り、それらの数字を処理するプログラムを作成する必要があります。プログラムは、入力された 2 つの値を自動的に処理する必要があります。これまでのコードは下にありますが、プログラムが数値を乗算する前に Enter キーを押す必要があります。ユーザーは Enter キーを 3 回押す必要はなく、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 を入力し、Enter キーを押します
  2. 数字の 2 を入力し、Enter キーを押します
  3. 何も入力せずエンターを押す
  4. プログラムは乗算された数を出力します

しかし、これはユーザーが現時点でプログラムを使用する方法です。

  1. 数字の 1 を入力し、Enter キーを押します
  2. 数字の 2 を入力し、Enter キーを押します
  3. プログラムは乗算された数を出力します

もちろん、私のプログラムは割り当てのために何か違うことをしなければなりませんが、ここで説明しやすくするために少し変更しました。

事前に助けてくれてありがとう!

4

4 に答える 4

1

あなたは学校の宿題をしているのですから、私は別の提案をします。紛らわしい「条件付きの宿題」をなくすことです。あなたがこれをどこかで見たことがあることは知っていますし、これからも多くの場所で目にすることになるでしょうし、それを熱心に提唱する人に出くわすことさえあるでしょうが、物事を混乱させる傾向があると思います. どうですか:

for (int i=0; i<2; i++)
{
  String number = reader.readLine();
  if (i == 0) { height = Integer.parseInt(number); }
         else { width = Integer.parseInt(number); }
}
于 2013-10-28T19:12:29.803 に答える
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);
}
于 2013-10-28T19:01:41.497 に答える