开发者

String array logic question with java I/O

开发者 https://www.devze.com 2022-12-28 06:46 出处:网络
I need to read a line like this from a file: 5 Chair 12.49 EDIT: I want to be able to have more lines of data.

I need to read a line like this from a file: 5 Chair 12.49 EDIT: I want to be able to have more lines of data.

I need to separate each word/numbe开发者_StackOverflow中文版r into different data types. First one is an int, second is a String, third is a double. Then I need to have them formatted like this: Item: Chair Price: $12.49 Quantity: 5

Now I know how to format, the only problem I am having is parsing the string elements into their respected data types (int, string, double).

I've tried:

String [] lines = lineInput.split(" ");
for(String displayLines : lines) {
    bufferedWriter.write(displayLines);
    bufferedWriter.newLine();
    System.out.println(displayLines);
}

but that only separates each string into a new line and I couldn't for the life of me figure out how to have each line check if it's an int, string or double.

Then I was messing with substring, but couldn't get that to work. I even thought of using mod % function and if:

if(lines.length % 2 == 0) {it's a string}; 

but that would only work for the first line.

Please believe me when I say i've tried this on my own and am not just making some half-trying effort. I just giving up. StackOverFlow, you're my only hope :(


If you have lines with the format [int] [String] [double], you can do:

String [] line = lineInput.split(" ");
int x = Integer.parseInt(line[0]);
String s = line[1];
double d = Double.parseDouble(line[2]);

You can modify this as necessary to handle lines with different formats.


I'm confused as to why you're splitting lines based on spaces.

But anyway, I think to solve your problem look at Integer.parseInt(), Double.parseDouble(). If you need to check something is a number, you could use an appropriate regular expression (see the String.matches() method). Or a dirty way that might work for your case is to call one of the parsing methods and see if it throws an exception...

You could also look at the Scanner class, but this may be overkill for what you need.


First, a small nit: calling the string array into which you split your line "lines" is misleading. Warning: not compiled or tested.


    String [] words = lineInput.split(" "); 
    if (words.length != 2) 
       System.err.println ("Error parsing line [" + lineInput + "]: " + wrong number of tokens on line");
    else
       try {
         int numberOfItems = Integer.parseInt(words[0]);
         String itemName = words[1];
         double itemPrice = Double.parseDouble(words[2]);
         System.out.println (itemName + " Price: $" + itemPrice + " Quantity: " + numberOfItems);
       } catch (NumberFormatException ex) {
          System.err.println ("Error parsing line [" + lineInput + "]: " + ex);
       }
    } 

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号