Ansh Shrivastava Ansh Shrivastava - 4 months ago 8
Java Question

Java Not Using the Scanner Class Correctly

I am a novice programmer, and this may seem like a very simple question to fix, but I am quite stuck, even after looking around for 2 hours or so. My code is pasted below, and the only problem is that the scanner class is not asking for an input. (To decide to use Gallons to Liters or Liters to Gallons) I would really appreciate if someone helped me out with this :D

import java.util.Scanner;
public class GallonsToLiters {

public static void main(String[] args) {
System.out.println("Do you want liters or gallons? Enter a 10 for gallons to liters, and anything else for liters to gallons.");

Scanner test = new Scanner(System.in);


if (test.equals (10)){
double gallons, liters;
Scanner console = new Scanner(System.in);

System.out.println("Enter an amount of gallons --> ");
gallons = console.nextDouble();
liters = gallons * 3.785;
// "%.2f" means that it rounds to 2 dec places. If you change #, that is how many decimal places it rounds to
System.out.printf("Amount in liters " + "%.2f",liters);
}
else{
double liters01, gallons01;
Scanner console01 = new Scanner(System.in);

System.out.println("Enter an amount of liters --> ");
liters01 = console01.nextDouble();
gallons01 = liters01 / 3.785;
// "%.2f" means that it rounds to 2 dec places. If you change #, that is how many decimal places it rounds to
System.out.printf("Amount in gallons (Rounded) " + "%.2f",gallons01);




}

Answer

No need to declare Scanner many objects just once, not declare different variables for gallons and liters for each conditional structure

Scanner reader = new Scanner(System.in);
double gallons, liters;
int op;
System.out.println("Do you want liters or gallons? Enter a 10 for gallons to liters, and anything else for liters to gallons.");

 op = reader.nextInt();

if (op==10){

        System.out.println("Enter an amount of gallons --> ");
        gallons = reader.nextDouble();
        liters = gallons * 3.785;
        // "%.2f" means that it rounds to 2 dec places. If you change #, that is how many decimal places it rounds to
        System.out.printf("Amount in liters " + "%.2f",liters);
}
 else{


        System.out.println("Enter an amount of liters --> ");
        liters = reader.nextDouble();
        gallons = liters/3.785;
        // "%.2f" means that it rounds to 2 dec places. If you change #, that is how many decimal places it rounds to
        System.out.printf("Amount in gallons (Rounded) " + "%.2f",gallons);
        }
}