Need to close out java with the letter q

6.6k Views Asked by At

I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.

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

There are 3 best solutions below

0
On

Do this to have the user input a letter

Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!

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
}
1
On

This looks like homework ;-)

One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:

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();
}
1
On

use a do-while loop in your main method as below

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

you would also want to have a try-catch block to handle numberFormatException