My Scanner input gets skipped and code gets terminated

116 Views Asked by At

I am writing a "Gallons to Liters and vice versa" program in Java, but once I finished my program, i gave it the first run. I displayed the system outputs, like expected, but then it skipped the user input stage of my program.

import java.util.Scanner;

public class Main {
    private static void intro(String[] args) {
        final Scanner galOrLit = new Scanner(System.in);

        System.out.println("[1] => Gallons to Liters");
        System.out.println("[2] => Liters to Gallons");

        if ("1".equals(galOrLit)) {
            galToLit(args);
        } else if ("2".equals(galOrLit)) {
            litToGal(args);
        }
    }

    private static void galToLit(String[] args) {
        double liters;

        System.out.println("Enter Gallons: ");
        final Scanner gallons = new Scanner(System.in);

        int input = gallons.nextInt();
        liters = input * 3.7854;

        System.out.println("\n" + input + " gallons is " + liters + " liters.");
    }

    private static void litToGal(String[] args) {
        double gallons;

        System.out.println("Enter Liters: ");
        final Scanner liters = new Scanner(System.in);

        int input = liters.nextInt();
        gallons = input / 3.7854;

        System.out.println("\n" + input + " liters is" + gallons + " gallons.");
    }

    public static void main(String[] args) {
        intro(args);

    }
}

I tried to final my Scanners, since I had multiple in one class, following this post. I was expecting my code to work smoothly, but it did no difference to the output. this is as far as I get with both versions of code.

1

There are 1 best solutions below

5
Skerdi Velo On

It looks like you are not actually reading any input from the user. You are only printing out the options to choose from, but you are not reading the user's input. You only to add one line:

String choice = scanner.nextLine();

Here is how it would look like:

private static void intro(String[] args) {
    final Scanner scanner = new Scanner(System.in);

    System.out.println("[1] => Gallons to Liters");
    System.out.println("[2] => Liters to Gallons");

    String choice = scanner.nextLine();

    if ("1".equals(choice)) {
        galToLit(args);
    } else if ("2".equals(choice)) {
        litToGal(args);
    }
}

Another thing, I suggest to not use nextLine(), but use: Integer.parseInt(scanner.nextLine()); for integer

So that line would look like this:

String choice = Integer.parseInt(scanner.nextLine());

Double.parseDouble(scanner.nextLine()); if you have any double Because if you input from string to int sometimes it doesn't work.

Hope this helps!