Home > database >  String input exceptions java
String input exceptions java

Time:09-22

I'm trying to use try and catch exceptions in case the user does not enter strings for username and integers for the pin code. but my code it's not working this is my code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner myuser = new Scanner(System.in);


        System.out.println("Enter your username: ");
            try {
            String username = myuser.nextLine();
            System.out.println("Your username is: "   username);
        }

        catch( Exception e) {
            System.out.println("Incorrect username! ");
        }
        System.out.println("Enter your pin code: ");
        int pin = myuser.nextInt();
        System.out.println("Your pin code is: "   pin);
    }
} ```
I tried to enter integers at the username to see if my try catch code works but the code doesn't recognize it as a problem.`Enter your username: 
234
Your username is: 234
Enter your pin code: 
`

    enter code here

CodePudding user response:

As I understand it, you want to check if your inputs are valid.

For username, nextLine() reads the given input as String, therefore, you can enter anything and it will be read as a string. Entering 123 as an input will be read as "123" and it won't throw any exceptions. If you want to check if the input string is alphabetic, i.e., contains only letters, you can refer to Check if String contains only letters

For pin code, you can check it with a try/catch block like this:

    System.out.println("Enter your pin code: ");
    try {
        int pin = myuser.nextInt();
        System.out.println("Your pin code is: "   pin);
    } catch(InputMismatchException e) {
        System.out.println("Incorrect pin!");
    }

It will check if the given pin code is a Java Integer, please note that given input can be a negative integer, and you should check it if you need to.

CodePudding user response:

Unfortunately the command line and Scanner has no validation; has no Exceptions.

String username = "";
do {
    System.out.println("Enter your username:");
    username = myuser.nextLine();
} while (username.isEmpty());

int pin = -1;
do {
    System.out.println("Enter your pin code: ");
    if (myuser.hasNextInt()) {
        pin = myuser.nextInt();
    } else if (myuser.hasNext()) {
        myuser.next();
        System.out.println("You must enter digits for the pin code.");
    }
    myuser.nextLine();
} while (pin == -1);

As you see Scanner.hasNextInt() should be queried, to check that an integer was provided. Any other non-numeric token could be consumed with next(). You could also use myuser.hasNextLine() when the typing user broke out of inputting.

This makes the use of Scanner circumstantial. I prefer reading lines and parsing them, say with Integer.parseInt(line). Otherwise I strongly advise to use the Console class which even has password entry (so the PIN does not show on the screen). This class however cannot be tested inside the IDE as a "console" in the IDE generally does a System.setIn(...) to capture the console. Console has nice prompts.

 // SAMPLE CODE
 char[] passwd;
 Console cons = System.console();
 if (cons != null) {
     String username = cons.readLine("User: ");
     passwd = cons.readPassword("Password for %s: ", username);
     if (passwd != null) {
         ...
         Arrays.fill(passwd, ' '); // Clear sensitive data in memory.
     }
 }

CodePudding user response:

As you have seen from other answers everything read from the scanner will be read as a String. Here is a little trick or workaround to check if someone enters a number.

public static void main(String[] args) {
    Scanner myuser = new Scanner(System.in);

    System.out.println("Enter your username: ");

    String username = myuser.nextLine();

    try {
        int valueInInteger = Integer.parseInt(username);
        System.out.println("Incorrect username! ");
    } catch (NumberFormatException e) {
        System.out.println("Your username is: "   username);
    }
    
    System.out.println("Enter your pin code: ");
    int pin = myuser.nextInt();
    System.out.println("Your pin code is: "   pin);
}

The trick here is if you parse a string it will throw a number format exception and you will be sure its a string.

  • Related