-1

我需要提示用户输入一个从 1 到 5 的数字。这是乘法表的大小。如果用户输入大于 5 的数字或负数,则程序告诉他们输入了无效数字并再次提示,如果用户输入 0,则停止程序的执行。有人可以帮我写这部分吗?

到目前为止我所拥有的:

// Beginning of class MultiplicationTable
public class MultiplicationTable {      

// Beginning of method main
public static void main(String[] args) {    

    /* Declare and initialize primitive variables */
    int result;

    /* Header */
    // First, print some space
    System.out.print("    ");

    // Then, print numbers from 1 to 5 across the top
    for (int j = 1; j <= 5; j++) {
        System.out.print("    " + j); 
    }
    System.out.println();

    /* Separator */
    // Print a dashed line
    for (int j = 1; j < 50; j++) {
        System.out.print("-");
    }   
    System.out.println();

    /* Values */
    // Outer loop: multipliers
    for (int outer = 1; outer <= 5; outer++) {  
        System.out.print(outer + " | ");

        // Inner loop: values
        for (int inner = 1; inner <= 5; inner++) { 

            // Calculate the value
            result = outer * inner;

            // Format the output
            if (result < 10) {

                // Here, we need an extra space if the result is 1 digit
                System.out.print("    " + result);
            }
            else {
                System.out.print("   " + result);
            }

        }   // End for inner

        System.out.println();

    }   // End for outer

} // End of method main

} // End of class MultiplicationTable
4

1 回答 1

0
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

int num;

while(true)
{
    try
    {
        System.out.print("Enter a number from 1 to 5: ");
        num = Integer.parseInt(input.readLine());
        if(num >= 1 && num <= 5)
             break;
        else
             System.out.println("Number must be between 1 and 5");
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    catch(NumberFormatException e)
    {
        System.out.println("Not an integer!");
    }
}

这将一直提示输入,直到他们输入 1 到 5 之间的整数。该整数将保存在“num”中。

于 2013-10-02T19:48:25.823 回答