写一个程序来读取两个数字,第一个小于第二个。程序将在两个数字之间写入所有数字

时间:2013-10-22 21:35:45

标签: java while-loop counter jgrasp

//所以我写了这个:(那里的输出)

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 个答案:

答案 0 :(得分:4)

int counter=num1;

您为循环的每次迭代创建了一个新的counter变量 因此,它们都具有相同的价值。

它永远运行,因为你的循环条件永远不会是假的(你永远不会改变num1num2)。

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

答案 2 :(得分:0)

作为新手程序员,我会使用for循环。这将更简单,更容易:

for(ctr=num1;ctr<=num2;ctr++)
   s.o.p(ctr)

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