-6

//だから私はこれを書いた:(出力はそこにある)

import java.util.Scanner;
public class E7L6{
public static void main(String[]args){
int num1, num2;
Scanner keyboard= new Scanner(System.in);
System.out.print("Type two numbers:");
num1= keyboard.nextInt();
num2= keyboard.nextInt();

if(num1<num2){
   while(num1<=num2){
   int counter=num1;
   System.out.print(counter+" "+num2);
   counter=counter+1;
   }}
else{
   System.out.print("Error: the first number must be smaller than the second");
}   
  }}

Output:
 ----jGRASP exec: java E7L6
Type two numbers:4 124
 4 4 4 4 4 4 4 4 4
 ----jGRASP: process ended by user.

//非常に多くの 4 の繰り返しがあり、どこが間違っているのか教えてもらえますか? ありがとう!!

4

4 に答える 4

4
int counter=num1;

counterループの反復ごとに新しい変数を作成しました。
したがって、それらはすべて同じ値を持ちます。

ループ条件が false になることはありません (num1またはを変更することはありませんnum2) ため、永久に実行されます。

于 2013-10-22T21:36:59.260 に答える
0
  while(num1<=num2){
   int counter=num1;
   System.out.print(counter+" "+num2);
   counter=counter+1;
  }

これは無限ループに陥ります。while ループの条件を変更する必要があります。

// 変更されたコード - 完全なコード。

import java.util.Scanner;

public class E7L6 {
    public static void main(String[] args) {
        int num1, num2;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type two numbers:");
        num1 = keyboard.nextInt();
        num2 = keyboard.nextInt();

        if (num1 < num2) {
            int counter = num1;
            while (counter <= num2) {
                System.out.print(counter + " ");
                counter = counter + 1;
            }
        } else {
            System.out
                    .print("Error: the first number must be smaller than the second");
        }
    }
}
于 2013-10-22T21:39:20.727 に答える