i want the question to repeat but if the user entered -1 i want the program to stop?

59 Views Asked by At

*i want the question to repeat but if the user entered -1 i want the program to stop ? *

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 + " ");}}}





}}

2

There are 2 best solutions below

0
On BEST ANSWER
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 + " ");
                }
            }
        }
    }
}
5
On

Using a loop is a more efficient solution but I will post the recursive solution because it's a good concept to understand. One of the big downsides of recursion in this case is the possibility of overflowing the stack, even though in this case it would be unlikely.

You can call the main method recursively in your default switch statement case.

        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);
        }

Sidenote: you should really work on improving your formatting. It is very difficult to read your code when the brackets are all lined up like that.