Stupid question in java

Solved
moussecp Posted messages 61 Status Member -  
 javabaka -
Hello,

It's silly, but I can create classes, manage a lot of things and all... but I don't know which line of code allows the user of the program to input values.

An example to be a bit clearer.
Let's say I want at a certain point in my program for the user to input two numbers that will be added together and displayed on the screen...

Well, I don't know how to do that. In C++, you have to do something like
 int a, b; cin >> a >> b >> endl; cout << a+b << endl;

but in Java, no idea...

Does anyone know how to help me?

Thanks.
Configuration: Windows XP Firefox 2.0.0.12

2 answers

  1. Godboss Posted messages 69 Status Member 18
     
    Hello,
    It's true that if you don't know, it's not easy.

    You need to use the Scanner class (there are other solutions using streams (InputStream...), but this one is not too complicated).

    In your Java program, you need to import the Scanner class (available starting from Java 5)
    That is: import java.util.*;

    Then in your program do:

    Scanner scan=new Scanner(System.in);
    //Then use scan to read what you want, for example:
    String s=scan.next(); //Expects a string
    int nb=scan.nextInt(); //Expects a number
    ...
    ...
    ...
    You have other methods to read other things; to know about them, check the Java 5 or 6 API
    or if you are developing in Eclipse, you can see them

    P.S.: For it to work, you must be developing in JAVA 5 or higher.
    1
    1. moussecp Posted messages 61 Status Member
       
      Thank you very much, it works perfectly.

      At first glance, I thought it looked really complicated for something so simple, but in the end, it's really easy.

      Thank you again.
      0
      1. Godboss Posted messages 69 Status Member 18 > moussecp Posted messages 61 Status Member
         
        You're welcome, glad to have been able to help you.
        0
  2. javabaka
     
    I use a BufferedReader

    example:
     String file = ""; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is the name of your file?"); file = keyboard.readLine(); 


    if you want an int from the keyboard, you do:

     int file = ""; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("What is the number of your file?"); file = Integer.parseInt(keyboard.readLine()); 


    and to make sure it's a number, you enclose it in a try-catch block (handle exceptions)
    0