0

This is a code I have developed to separate inputs by the block (when a space is reached):

import java.util.Scanner;
public class Single {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Three Numbers:");
        String numbers = in.next();
        int length = numbers.length();
        System.out.println(length);
        int sub = length - length;
        System.out.println(sub);
        System.out.println(getNumber(numbers, length, sub));
        System.out.println(getNumber(numbers, length, sub));
        System.out.println(getNumber(numbers, length, sub));
    }
    public static double getNumber(String numbers, int length, int sub){
        boolean gotNumber = false;
        String currentString = null;
        while (gotNumber == false){
            if (numbers.substring(sub, sub + 1) == " "){
                sub = sub + 1;
                gotNumber = true;
            } else {
                currentString = currentString + numbers.substring(sub, sub);
                sub = sub + 1;
            }
        }
        return Double.parseDouble(currentString);
    }
}

However, it only reads the first set for the string, and ignores the rest. How can I fix this?

2 Answers 2

1

The problem is here. You should replace this line

String numbers = in.next();

with this line

String numbers = in.nextLine();

because, next() can read the input only till the first space while nextLine() can read input till the newline character. For more info check this link.

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

Comments

0

If I understand the question correctly, you are only calling in.next() once. If you want to have it process the input over and over again you want a loop until you don't have any more input.

while (in.hasNext()) {
    //do number processing in here
}

Hope this helps!

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.