0

I have a standard input that contains lines of text. Each line contains 2 numbers that are separated by a comma. I need to separate the two numbers so that I can use them in another function. I don't know what would be a good way to read each line, separate the numbers and then use them to call function until there are no more lines to be read. I read the documentation regarding InputStreamReader and BufferedReader, however, since I'm relatively new to java they didn't make much sense.

public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);

try {

    double num1 = Double.parseDouble(in.readLine());
    double num2 = Double.parseDouble(in.readLine());
    Main.function(num1,num2);
}

2 Answers 2

2

When you call in.readLine() then you get a string, probably something like "42.1,100.2". The next step would be splitting the string and after that you can convert the split string(s) to numbers.

String line = in.readLine();                  // read one line
String[] parts = line.split(",");             // split the line around the comma(s)
double num1 = Double.parseDouble(parts[0]);   // convert the first part to double
double num2 = Double.parseDouble(parts[1]);   // convert the second part to double
Main.function(num1, num2);

Note that this only reads from one line in the file (many lines -> looping) and that this only works correctly when the input is well formatted. You probably want to lookup the trim() method on String.

Sign up to request clarification or add additional context in comments.

2 Comments

When I do this it says index out of bounds for index[1] since length is only 1.
Then your input is not "2 numbers, separated by a comma". That's why I mentioned: this snippet only works with correct input. If you just enter one number, then it fails with exactly that error.
0

Double is not recognize the commas instead you will have to take the input string and replace all commas with empty strings. e.g. you have this input

String input = "123,321.3" ;
input = input.replaceAll("," , "");

in result you will have this

input -> "123321.3"

Then you can parse the string to double.

Hope it will help. Regards , Erik.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.