Program not waiting for input???????????
807600Jul 4 2007 — edited Jul 4 2007When I use keyboard.next() the program wiats for input, but when I use keyboard.nextLine() it doesn't wait for input. Can anyone tell me why? I am new to Java and this is the first programming language I have ever learnt. The problem is when option b is selected and the program returns no errors when compiled.
//Written SH 6/7/07
//This programme allows the user 3 options to either,
//print a number pattern, reverse a string or exit the programme.
import java.util.Scanner;
public class Assignment1 {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println();
System.out.println("Print Pattern and Reverse String Menu");
System.out.println();
System.out.println("A. Print a pattern");
System.out.println("B. Reverse a string of text");
System.out.println("X. Exit the programme");
System.out.println();
System.out.print("Select an option from the menu (A, B or X): ");
char option = keyboard.next().charAt(0);
if (option == 'A' || option == 'a') {
System.out.println();
System.out.print("Enter the number of rows in the pattern to be printed: ");
int rows = keyboard.nextInt();
System.out.print("Enter character to be printed: ");
char character = keyboard.next().charAt(0);
for (int i = 1; i<=rows; i++) {
for (char j=1; j<=i; j++)
System.out.print(character + " ");
System.out.println();
}
}
else if (option == 'B' || option == 'b') {
System.out.println();
System.out.println("Enter a string of text to be reversed: ");
String text = keyboard.nextLine();
int last = text.length();
String reverse = text.substring(last,0);
System.out.println("The reverse of the string of text you entered is: " + reverse);
System.out.println();
}
else if (option == 'X' || option == 'x') {
System.out.println("Exiting the programme...");
System.out.println();
System.exit(0);
}
else {
System.out.println("Error! You did not select a valid option from the menu");
}
}
}