0

Need to create a 2 codes for the program. One to verify and integer is input, the second to verify that a capital letter between A-H has been entered. Here is what I have so far, new to Java and learn more by doing than reading. Am having an issue that it is throwing the error for letters instead of anything not A-H

package userinput;
    
import java.util.Scanner;

public class UserInput {

    public static void main(String[] args) {
        // TODO code application logic here 
        Scanner keyboard1 = new Scanner(System.in);

        int number;
        do {
            System.out.print("Enter An Integer: ");
            while (!keyboard1.hasNextInt()) {
                String input = keyboard1.nextLine();
                System.out.printf("Invalid Input. Enter An Integer: ", input);
            }
            number = keyboard1.nextInt();
        } while (number < 0);
        System.out.println("You have entered integer: " + number);
        
        Scanner keyboard2 = new Scanner(System.in);
        char character;
        do {
            System.out.print("Enter A Character <A-H>: ");
            while (!keyboard2.hasNextInt()) {
                String input2 = keyboard2.next();
                System.out.printf("Invalid Input. Enter A Character: ", input2);
            }
            character = keyboard2.next().charAt(0);
        } while (character >= 'A' && character <= 'H');
        System.out.println("You entered character: " + character);
    }
}

Here is a sample of the console for a run:

Enter An Integer: 53
You have entered integer: 53
Enter A Character <A-H>: l
Invalid Input. Enter A Character: L
Invalid Input. Enter A Character: 5
You entered character: 5
Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • 1
    Once you have read the string you can do 2 things: a) `Integer.parseInt(input)` to try to parse it into an `int` - catch the exception this might throw to report the input was not an integer and b) check the input length is 1 and check the first character (via `input2.charAt(0)`) is `>= 'A'` and `<= 'H'` – Thomas Sep 24 '20 at 20:23
  • What does this code do? Does it misbehave, and if so, how? Providing sample output would be great. – CryptoFool Sep 24 '20 at 20:23
  • Still new and not certain how to word the coding, been working on this a bit too long so now just getting a bit burnt out. – mrdanthedeadman Sep 24 '20 at 20:39
  • Change `String input2 = keyboard2.next();` to `String input2 = keyboard2.nextLine();` and read the accepted answer of duplicate question. – Bohemian Sep 24 '20 at 20:40

0 Answers0