Arianule
Arianule

Reputation: 9043

standard console input

Good afternoon

I would just like to know the easiest way for standard Console input with java. When it come to int or double input for example in C# it is simple. What would the easiest way be of doing this in java.?

double a;
        Console.WriteLine("Please enter the value");

        a = double.Parse(Console.ReadLine());

        Console.WriteLine("thank you for entering " + a);

Kind regards Arian

Upvotes: 5

Views: 9295

Answers (5)

Ali Hasan
Ali Hasan

Reputation: 1075

Try this

 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Please enter the value");      
      double a = in.readDouble();
      System.console().writer().println("thank you for entering " + a);

Upvotes: 1

Yanki Twizzy
Yanki Twizzy

Reputation: 8001

JDK 5.0 & above provides a feature to read input from console - Java.util.Scanner. The code below reads a String and an Integer from the console and stores them in the variables.

import java.util.Scanner;
public class InputExp {
   public static void main(String[] args) {
       String name;
       int age;
       Scanner in = new Scanner(System.in);

   // Reads a single line from the console 
   // and stores into name variable
   name = in.nextLine();

   // Reads a integer from the console
   // and stores into age variable
   age=in.nextInt();
   in.close();            

   // Prints name and age to the console
   System.out.println("Name :"+name);
  System.out.println("Age :"+age); 

} }

Upvotes: 1

mcfinnigan
mcfinnigan

Reputation: 11638

use java.util.Scanner - it has support to read numbers from STDIN.

Upvotes: 1

erimerturk
erimerturk

Reputation: 4288

try {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);
      String s = br.readLine();
      DecimalFormat df = new DecimalFormat();
      Number n = df.parse(s);
    double d = n.doubleValue();
     } catch (IOException e) {
        e.printStackTree();
     } catch (ParseException e) {
       e.printStackTree();
     }

or

   try {
          InputStreamReader isr = new InputStreamReader(System.in);
          BufferedReader br = new BufferedReader(isr);
          String s = br.readLine();
          double d = Double.parseDouble(s);

        } catch (IOException e) {
         e.printStackTree();
        } catch (ParseException e) {
         e.printStackTree();
        }

Upvotes: 1

MByD
MByD

Reputation: 137322

The direct translation is:

Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value");
double i = Double.parse(scan.nextLine());
System.out.println("thank you for entering " + i);

But you can also use Scanner#nextDouble():

Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value");
double i = scan.nextDouble();
System.out.println("thank you for entering " + i);

Upvotes: 11

Related Questions