mercredi 26 juin 2019

Beginner needs help JAVA

I'm new to coding and Java. I learned the theory the past two days, now im trying to make it work getting some practice

i've tried moving it around and stuff, can't really still tell

import java.util.Scanner;
public class JavaLessonTwo
{
    static Scanner userInput= new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.print("Your favourite number: ");
        if(userInput.hasNext()) {
            int numberEntered=userInput.nextInt();
            System.out.println("You entered "+numberEntered);

        }  else {

            System.out.println("Enter an integer next time");
        }

    }
}

Error is :

Your favourite number: asd
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at JavaLessonTwo.main(JavaLessonTwo.java:9)

Process finished with exit code 1

I want to make it so if you enter for example letters instead of integers you get a msg ''Enter an integer next time"

Aucun commentaire:

Enregistrer un commentaire