0
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String characters;
        Scanner scan = new Scanner(System.in);
        boolean quit = false;

        do {
            System.out.println("USD to SEK converter");
            System.out.println("Enter 'quit' to exit the program");
            System.out.print("Enter USD amount: ");

            if (scan.hasNextDouble()) {
                double usd = scan.nextDouble();
                double sek = usd * 11.2;
                System.out.println(sek);
            }else if(scan.hasNextLine()) {
                characters = scan.nextLine();
                System.out.println(characters);
                if (characters.equals("quit")) {
                    quit = true;
                }
            }
        }while (!quit);
    }
}

I am making a USD to SEK converter and when I input 1 +, I first get the conversion of 1 USD to SEK and then get +. Why is the program first checking 1 and then + and not both at the same time? If I input 1+, I get 1+. No conversion of 1. If I enter 1+2 I get 1+2 and when I enter 1 + 2 I first get the conversion on 1 USD to SEK and then + 2.

  • 1
    any `next` or `hasNext` method that are not *considering* a line (`nextLine` or `hasNextLine`) work on TOKENS, which are delimited by white spaces (if not changed) - Also be aware of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo?r=SearchResults&s=1%7C240.5121) - Anyway – user16320675 Oct 19 '22 at 14:34
  • Because `hasNextDouble` and `nextDouble` will read the next double in your input and not necessarily consume a complete line. In the case of `"1 +"` the next double it can read is `1`. – OH GOD SPIDERS Oct 19 '22 at 14:35
  • @user16320675 I only want the user to be able to input doubles and no letters or + or - etc. – Nicholas Chill Oct 19 '22 at 14:54
  • @OHGODSPIDERS How would I then check the whole line at once? – Nicholas Chill Oct 19 '22 at 14:56
  • You could just always use `nextLine()` method to get the whole line as a String, then check what that String contains like if it is `"quit"` and if not if it is possible to parse the whole line to a double via using `Double.parseDouble` – OH GOD SPIDERS Oct 19 '22 at 15:06

0 Answers0