Reputation: 23
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
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
.
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
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
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