-1

我对编程很陌生。我需要它在最后说“输入字母 q 退出或任何其他键继续:”。如果输入 q,它将终止。如果您输入任何其他字符,它会提示您输入另一个正整数。

import java.util.Scanner;

public class TimesTable {
    public static void main(String[] args) {
       Scanner input = new Scanner(System.in);


       System.out.println("Enter a postive integer: ");
       int tableSize = input.nextInt();
       printMultiplicationTable(tableSize);

    }
    public static void printMultiplicationTable(int tableSize) {
        System.out.format("      ");
        for(int i = 1; i<=tableSize;i++ ) {
            System.out.format("%4d",i);
        }
        System.out.println();
        System.out.println("------------------------------------------------");

        for(int i = 1 ;i<=tableSize;i++) {
            System.out.format("%4d |",i);
            for(int j=1;j<=tableSize;j++) {
                System.out.format("%4d",i*j);
            }
            System.out.println();
        }
    }
}
4

3 回答 3

0

这样做是为了让用户输入一个字母

信息:
System.exit(0) 退出程序,没有错误代码。
nextLine() 等待用户输入字符串并按回车。
nextInt() 等待用户输入 int 并按回车。
希望这可以帮助!

Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
    System.exit(0);
}else {
    System.out.println("Enter a postive integer: ");
    int i = input.nextInt();
    //continue with your code here
}
于 2016-05-11T03:57:38.293 回答
0

这看起来像家庭作业;-)

解决此问题的一种方法是将打印消息并接受输入的代码放入 while 循环中,可能类似于:

Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q') 
{     
    System.out.println("Enter a postive integer: ");
    int tableSize = input.nextInt();
    printMultiplicationTable(tableSize);
    System.out.println("Enter q to quit, or any other key to continue... ");
    nextByte = input.nextByte();
}
于 2016-05-11T04:03:34.893 回答
0

在您的主要方法中使用do-while循环,如下所示

do {
        System.out.println("Enter a postive integer: ");
        String tableSize = input.next();

        if (!"q".equals(tableSize) )
            printMultiplicationTable(Integer.parseInt(tableSize));

    }while (!"q".equals(input.next()));
    input.close();

您还希望有一个try-catch块来处理 numberFormatException

于 2016-05-11T04:04:03.777 回答