input java

h‮t‬tps://www.lautturi.com
input java

To input data in Java, you can use the Scanner class or the BufferedReader class.

Here is an example of how to use the Scanner class to input different data types:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int i = sc.nextInt();
        System.out.print("Enter a double: ");
        double d = sc.nextDouble();
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        sc.close();
    }
}

In this example, the Scanner class is used to read input from the console. The nextInt() method is used to read the next token in the input as an integer, the nextDouble() method is used to read the next token as a double, and the nextLine() method is used to read the rest of the line as a String.

Here is an example of how to use the BufferedReader class to input different data types:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter an integer: ");
        int i = Integer.parseInt(br.readLine());
        System.out.print("Enter a double: ");
        double d = Double.parseDouble(br.readLine());
        System.out.print("Enter a string: ");
        String str = br.readLine();
        br.close();
    }
}

In this example, the BufferedReader class is used to read input from the console. The readLine() method is used to read a line of input as a String, and the Integer.parseInt() method is used to parse the String as an integer, while the Double.parseDouble() method is used to parse the String as a double.

For more information on the Scanner class and the BufferedReader class in Java, you can refer to the Java documentation and the [Java tutorial](https://docs.oracle.com/en/java/javase/11/

Created Time:2017-11-01 22:29:52  Author:lautturi