java.util.scanner - How to read and add only numbers to array from a text file -


i'm learning java , have question regarding reading file want read numbers file contains strings well. here example of file:

66.56 "3 java 3-43 5-42 2.1 1 

and here coding: public class test {

public static void main (string [] args){       if (0 < args.length) {      file x = new file(args[0]);     try{      scanner in = new scanner( new fileinputstream(x)); arraylist<double> test = new arraylist<>(); while(in.hasnext()){      if(in.hasnextdouble()){       double f=in.nextdouble();        test.add(f);}     else              {in.next();} }  catch(ioexception e) { system.err.println("exception during reading: " + e); } } 

my problem add 66.56,2.1 , 1 doesn't add 3 after "3 or ignores 3-43 , 5-42 can tell me how skip strings , add doubles here? thanks

all said 3 ie; "3, 3-43 , 4-42 strings

either u read string , split , check number @ " , - or put in space between characters , integers. jvm after compilation treat string if cannot converted double. , file reader wont stop reading till @ least space or newline. hence code never work way intend unless said above.

solution 1:
change input file this:

66.56 " 3 java 3 - 43 5 - 42 2.1 1 

solution 2:
considering highly variable nature of input file posting solution made current input. if input changes more versatile algorithm need implemented.

public static void main(string[] args) {         file x = new file(args[0]);         try {             scanner in = new scanner(new fileinputstream(x));             arraylist<double> test = new arraylist<>();             while (in.hasnext()) {                 if (in.hasnextdouble()) {                     double f = in.nextdouble();                     test.add(f);                 } else {                     string s=in.next();                     if(s.contains("\"")){                         string splits[]=s.split("\"");                         test.add(double.parsedouble(splits[1]));                     }                     else if (s.contains("-")){                         string splits[]=s.split("-");                         test.add(double.parsedouble(splits[0]));                         test.add(double.parsedouble(splits[1]));                     }                 }             }             system.out.println(test);         } catch (ioexception e) {             system.err.println("exception during reading: " + e);         } } 

Comments

Post a Comment

Popular posts from this blog

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -