2013-10-22 40 views
-5

//所以我写这之间:(输出那里)编写一个程序来读取两个数字,第一个小于第二个数字。该计划将写入所有号码的两个数字

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重复谁能告诉我在哪里,我错了?谢谢!!

+0

同样的问题 - 所有你正在做的是求一个答案。啧。 –

回答

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"); 
     } 
    } 
} 
+0

谢谢!我现在有一个数字序列,但它不限于num2(例如4 10)它不会停在10 – Mufasa

+0

我已经更新了完整的代码。它为我工作。只需比较你的代码。 – Reji

+0

太棒了!谢谢!! :D – Mufasa

4
int counter=num1; 

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

它永远运行,因为您的循环条件永远不会是错误的(您永远不会更改num1num2)。

+0

你说得对,那我该怎么办? – Mufasa

+0

我修改它以首先把int计数器,我现在有一个数字序列,但仍然永远运行,(1 10)不停止在10它继续了吗? – Mufasa

+0

@BaderK:正如我在回答结束时所说的,你需要改变你的循环,以便知道何时停止。 – SLaks

0

作为一个新手程序员,我会用循环来代替。它会更简单,更轻松:

for(ctr=num1;ctr<=num2;ctr++) 
    s.o.p(ctr) 
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++; 
    } 
相关问题