*我想重复这个问题,但是如果用户输入-1,我希望程序停止吗? *
public class Q2 {
public static void main (String [] args) {
int N ;
Scanner input = new Scanner (System.in) ;
System.out.println("Enter an integer to print it's multiplication table, -1 to exit ") ;
N = input.nextInt() ;
switch (N) {
case -1 : break ;
default :
for (int t=1 ; t <= N ; t++){
System.out.println (" Multiplication table of " + t );
for ( int i = 0 ; i <= 10 ; i++ ) {
System.out.println ( t + "*" + i + " = " + i*t + " ");}}}
}}
您可以在默认值:switch语句中递归调用main方法。
switch (N) {
case -1:
break;
default:
for (int t=1 ; t <= N ; t++){
System.out.println (" Multiplication table of " + t );
for ( int i = 0 ; i <= 10 ; i++ ) {
System.out.println ( t + "*" + i + " = " + i*t + " ");
}
main(args);
}
}
旁注,您应该真正改善格式。像这样将方括号全部对齐时,很难阅读代码。