my teacher only teach to read char with system.in.read(),is there any way to read a char with scanner?? and is a String of "a" same as a char of 'a' .
Printable View
my teacher only teach to read char with system.in.read(),is there any way to read a char with scanner?? and is a String of "a" same as a char of 'a' .
Hello lotus,
You can read a char with the Scanner class like this:
Code :import java.util.Scanner; public class lotus { /** * JavaProgrammingForums.com */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); char[] myChar; myChar = input.toCharArray(); System.out.println(myChar); } }
The Scanner class doesn't have .nextChar(); unlike .nextDouble(); .nextInt(); etc.
Basically you use the Scanner class to read in the user input as String and then you need to convert the String to char.
A char is a single character, a String is ment to be a sequence of characters. String is an full-blown object, a char primitive data type is just two bytes in unicode.
I never use a char variable nowdays. Always just stick it in a String.
That's a problem, though if you want to read in the next char after... It's only going to return the first char of each word :P
To read in a single character, you can use the CharArrayReader class or the BufferedReader class. Actually, I think most of Reader's sub classes should be able to read in a single character.
why do you use a char[]??? and not char myChar;
because im at the final stage of my project, i have users input choice of 1 2 or 3 , but if a user inpuuts a non int number like a it gives a error, so if i want to solve these type of problems i have a String choice and then convert it to whatever i want it to be?
You'd want to make sure you use char[] for your passwords though :D
// Json
Take a read of this:
String (Java Platform SE 6)