Inputting numbers in java?

Why do you have 2 read statements?

This works fine on my comp (Assuming 5 gallons is actually 22.5 litres)

Code:
import java.util.Scanner;

public class GallonsToLitres
{

    public static void main(String[] args)
    {
    	System.out.println("How many gallons do you want to be converted?");
    	
    	Scanner input = new Scanner(System.in);
     	int gallons = input.nextInt();
     	
     	System.out.println(gallons + " gallons is " + (gallons * 4.5) + " litres");
    }//End of main()
}//End of class

I must look into scanners more, when I was learning Java at Uni we used buffered input readers but these are much easier to use...
 
Last edited:
Energize said:
It's just that it seems to be much more typing, wouldn't it make sense to only use objects where nessecary to reduce the amount of code?

If u think like this then you should forget Java and think about using Basic!! :)
 
Chrisss said:
Scanner input = new Scanner(System.in);
String line = input.nextLine();
int a = Integer.parseInt(line);

Just use nextInt() and read it as an int?
Code:
Scanner input = new Scanner(System.in);
int number = input.nextInt();
 
Ok this works,

Code:
import javax.swing.*;
 
public class galtolit
{
   public static void main(String[] args)
   {
      String i;
      int gallons;
      i = JOptionPane.showInputDialog("Enter the number of gallons you want to be converted");
      gallons = Integer.parseInt(i);
      System.out.println(gallons+" gallons is "+gallons*4.6+" litres");
      System.exit(0);
   }
}

but when I try to get rid of the graphics, it doesn't.

Code:
public class galtolit
{
   public static void main(String[] args) throws Exception
   {
      String i;
      int gallons;
      i = (String) System.in.read("Enter the number of gallons you want to be converted");
		System.in.read();
      gallons = Integer.parseInt(i);
      System.out.println(gallons+" gallons is "+gallons*4.6+" litres");
      System.exit(0);
   }
}

Instead I get "ConvertString.java:8: cannot find symbol
symbol : method read(java.lang.String)
location: class java.io.InputStream
i = (String) System.in.read("Enter the number of gallons you want to be converted");
........................... ^"

I suppose I can live with using the graphics box, but it's more stuff to remember.
 
Last edited:
Presumably because System.in.read() doesn't take in any arguments - you're giving it a String.

And why are you calling in.read twice?
 
Chrisss said:
Presumably because System.in.read() doesn't take in any arguments - you're giving it a String.

And why are you calling in.read twice?

Guide, says I need to put it in again to catch the user pressing enter.
 
Back
Top Bottom