james B
james B

Reputation: 11

How can I change input from integers to characters?

I have tried changing int to String and char but neither seemed to work. Any help is greatly appreciated

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your phrase: ");
        int phrase =  input.nextInt();
        System.out.println("You entered " + phrase);

        // closing the scanner object
        input.close();
    }
}

Upvotes: 0

Views: 56

Answers (1)

Ryan H.
Ryan H.

Reputation: 2593

Calling the nextInt() method attempts to get the next token as an int. If it is not an int, an InputMismatchException is thrown. If you enter input that can be represented as an int, then you will see your phrase printed.

Try this:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your phrase: ");
        String phrase = input.next();
        System.out.println("You entered " + phrase);

        // closing the scanner object
        input.close();
    }
}

next() returns the next complete token as a String.

java.util.Scanner documentation

As Lino has pointed out, if you intend on capturing multiple, seperated words, you can instead use nextLine() instead of next().

Upvotes: 1

Related Questions