-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变量。
因此,它们都具有相同的值。

它永远运行,因为你的循环条件永远不会是假的(你永远不会改变num1or 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 回答
0

作为一个新手程序员,我会改用 for 循环。它会更简单,更容易:

for(ctr=num1;ctr<=num2;ctr++)
   s.o.p(ctr)
于 2016-07-12T14:44:03.883 回答
0

干得好:

System.out.print("First:");
    int first = Integer.parseInt(reader.nextLine());
    System.out.print("Second:");
    int second = Integer.parseInt(reader.nextLine());
    while (first <= second) {
        System.out.println(first);
        first++;
    }
于 2018-03-03T23:01:36.393 回答