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' .
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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:
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.
Please use [highlight=Java] code [/highlight] tags when posting your code.
Forum Tip: Add to peoples reputation by clicking the button on their useful posts.
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
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.
Last edited by helloworld922; July 28th, 2009 at 10:55 AM.
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
// Json
Please use [highlight=Java] code [/highlight] tags when posting your code.
Forum Tip: Add to peoples reputation by clicking the button on their useful posts.