我想重复这个问题,但是如果用户输入 -1 我想让程序停止?
i want the question to repeat but if the user entered -1 i want the program to stop?
*我想重复这个问题,但是如果用户输入 -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 + " ");}}}
}}
使用循环是更有效的解决方案,但我将 post 递归解决方案,因为这是一个很好理解的概念。在这种情况下,递归的一大缺点是可能会溢出堆栈,尽管在这种情况下不太可能。
您可以在默认的 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);
}
旁注:你真的应该努力改进你的格式。当括号都排成这样时,很难阅读你的代码。
import java.util.Scanner;
public class ContiniousProgramme {
public static void main(String [] args ) {
Scanner sc = new Scanner(System.in);
while(true) {
int N = sc.nextInt();
if(N == -1) {
break;
}
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 + " ");
}
}
}
}
}
*我想重复这个问题,但是如果用户输入 -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 + " ");}}}
}}
使用循环是更有效的解决方案,但我将 post 递归解决方案,因为这是一个很好理解的概念。在这种情况下,递归的一大缺点是可能会溢出堆栈,尽管在这种情况下不太可能。
您可以在默认的 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);
}
旁注:你真的应该努力改进你的格式。当括号都排成这样时,很难阅读你的代码。
import java.util.Scanner;
public class ContiniousProgramme {
public static void main(String [] args ) {
Scanner sc = new Scanner(System.in);
while(true) {
int N = sc.nextInt();
if(N == -1) {
break;
}
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 + " ");
}
}
}
}
}