How to read Json Data from online file?

Java Question - How do you read a 'char' data type from a file using Scanner class?

  • I am writing a pretty basic program for an entry level computer science class. I am importing data from a .txt file. The data looks like this: 1001A m 180 60 120 1002A f 250 20 310 1003A m 99 70 60 1004B m 200 40 100 1005B f 240 50 80 1006B f 180 60 120 I need to read each individual piece of data and assign it different variables by doing this: while (inputFile.hasNext()) { ID = inputFile.next(); sex = inputFile.next(); totalCholesterol = inputFile.nextInt(); HDL = inputFile.nextInt(); trig = inputFile.nextInt(); The problem is that the M and F characters (stands for male and female) cannot be read from the file with the sex = inputFile.next(); command because they are not Strings. The reason they MUST be char data types is that later in the program I must seperate the M from the F with switch statement like this: switch (sex) { case 'm': if (hdl < 40) hdlClassification = "LOW"; else if (hdl <= 59) hdlClassification = "AVERAGE"; else hdlClassification = "HIGH"; break; case 'f': if (hdl < 50) hdlClassification = "LOW"; else if (hdl <= 59) hdlClassification = "AVERAGE"; else hdlClassification = "HIGH"; break; } There are other variables here obviously...but I need to know to read the M and F from the file, and then save it as a char. Since Scanner supports tokens for all of the Java language's primitive types (except for char) I don't know how to do it...

  • Answer:

    Just use the charAt(0) method like this: char sex = inputFile.next().charAt(0);

Todd and Jennifer at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

You can read "f" and "m" as strings of length 1 with Scanner.next(). Note, your program isn't very robust. You should try something like: while (in.hasNextLine ()) { String [] tokens = in.nextLine ().split (" "); if (tokens.length < 5) { // error } else { id = tokens [0]; sex = tokens [1]; // or sex = tokens [1].charAt (0) (but make sure tokens[1].length > 0 too to be robust) ... } }

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.