B. Moore
B. Moore

Reputation: 23

change a scanner to a char variable instead of a int or double data type

import java.io.*;
import java.util.*;
public class Test
{
    public static void main(String args[])
    {
        Scanner kbr = new Scanner(System.in);
        System.out.print("Enter Player's Name: ");
        double n = kbr.nextInt();
        System.out.print(n);
    }
}

Can I change this to

char n = kbr.nextInt()

or how can I get it to look for a character string instead of an int.

Upvotes: 0

Views: 197

Answers (3)

Digvijaysinh Gohil
Digvijaysinh Gohil

Reputation: 1455

If you wants to get only first character of the typed string then

char c = kbr.next().charAt(0);

works fine.
However it allows to input more than single character but as soon as you hit enter,
it will store first character in char c.

For example

import java.io.*;
import java.util.*;

class Test
{
    public static void main(String args[])
    {
        Scanner kbr = new Scanner(System.in);
        System.out.print("Enter Character: ");
        char n = kbr.next().charAt(0);
        System.out.print(n);
    }
}

Input: Hello

Output: H

Upvotes: 0

user5234185
user5234185

Reputation:

Something like this?

import java.io.*;
import java.util.*;


class Test
{
    public static void main(String args[])
    {
        Scanner kbr = new Scanner(System.in);
        System.out.print("Enter Player's Name: ");
        String n = kbr.nextLine();
        System.out.print(n);
    }
}

Upvotes: 0

Krishna Chalise
Krishna Chalise

Reputation: 145

you can do this as alternative:

import java.io.*;
import java.util.*;
public class Test
{
    public static void main(String args[])
    {
        try{
            Scanner kbr = new Scanner(System.in);
            System.out.print("Enter Player's Name: ");
            String n = kbr.readLine();
            //int z = Integer.parseInt();
            char z = n.charAt(0);
            System.out.print(n);
        }
        catch(IOException e){
            System.out.printl("IO ERROR !!!");
            System.exit(-1);
        }
    }
}

Upvotes: 1

Related Questions