2016-03-01 53 views
0

我试图提示用户输入一个介于1和12之间的值。如果他们输入的值超出此范围(EX -15),我需要继续提示直到他们进入一个在1-12的值。当用户输入一个指定范围内的值时(1-12)它需要打印一个时间表,其中包含整数1乘以输入数字的结果。到目前为止,我相信我有这个布局一些什么正确的,但我知道我失去了一些东西,但无法弄清楚这里的代码:试图让用户输入介于两个值之间

package times_Table; 

import java.util.Scanner; 

public class Times_Table { 

    public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 
     final int TOTAL = 5; 

     System.out.print("Enter an integer between 1 and 12:"); 
     int input = sc.nextInt(); 
     int numbers = input; 

     //If the input is out of the range 1-12 keep going 
     //If the input is in the range of 1-12 stop 

     //Need to find a way to keep looping if the integer inputed is  out of the range 1-12 
     while (numbers>1 && numbers<12) { 
      if (numbers<1 && numbers>12) { 
       for (int i = 1; i <= TOTAL; i++) { 
        for (int j = 1; j<=TOTAL; j++) { 
         System.out.print(i*j + "\t"); 
        } 
        System.out.println(); 
       } 
      } else { 
       if (numbers < 1 && numbers > 12) { 
        System.out.print("Enter an integer between 1 and 12:"); 
       } 
      } 
     } 
    } 
} 
+4

它会帮助你很多,如果你将通过代码在你的IDE调试步骤,看什么在发生每个陈述。你试过了吗? –

+0

你需要重做你的'if/else'流程。应该是数字在里面,做数学运算,否则用'Scanner'再次请求输入。现在你的while循环正在使if else循环无用。 –

+0

请注意澄清*它需要打印一个时间表,结果乘以整数1到输入数字... *? – aribeiro

回答

0

更改,而像这样:

while (keepGoing) { 
    while (numbers < 1 || numbers > 12) { 
     System.out.print("Enter an integer between 1 and 12:"); 
     numbers = sc.nextInt(); 
    } 

    for (int i = 1; i <= numbers; i++) { 
     for (int j = 1; j<=numbers; j++) { 
      System.out.print(i*j + "\t"); 
     } 
     System.out.println(); 
    } 
} 
+0

谢谢@Jordy帮助。 –

+0

很高兴我的回答有所帮助。对不起,但我不明白这一点“它需要打印一个时间表,结果是整数1乘以输入数字。” (对不起,英文不是我妈妈的舌头) –

+0

当输入范围内的值需要打印出包含许多行和列的时间表时。 EX说我使用2作为范围内的数字时间表显示与2行和2列。到目前为止,无论final int TOTAL = 5,我都将其设置为5的默认值。 –

1

推荐的重复提示模式将是一个do-while循环。

Scanner sc = new Scanner(System.in); 

int input; 
do { 
    System.out.print("Enter an integer between 1 and 12: "); 
    input = sc.nextInt(); 

    if (input < 1 || input >= 12) { 
     System.out.println("Invalid number input!"); 
    } 
} while (input < 1 || input >= 12); 

而这种打印表格

for (int i = 1; i <= input; i++) { 
    for (int j = 1; j <= input; j++) { 
     System.out.printf("%3d\t", i*j); 
    } 
    System.out.println(); 
} 

像这样

Enter an integer between 1 and 12: 11 
    1 2 3 4 5 6 7 8 9 10 11 
    2 4 6 8 10 12 14 16 18 20 22 
    3 6 9 12 15 18 21 24 27 30 33 
    4 8 12 16 20 24 28 32 36 40 44 
    5 10 15 20 25 30 35 40 45 50 55 
    6 12 18 24 30 36 42 48 54 60 66 
    7 14 21 28 35 42 49 56 63 70 77 
    8 16 24 32 40 48 56 64 72 80 88 
    9 18 27 36 45 54 63 72 81 90 99 
10 20 30 40 50 60 70 80 90 100 110 
11 22 33 44 55 66 77 88 99 110 121 
相关问题