To collect objective data in Java, you can use the Scanner
class to read input from the console or from a file. The Scanner
class provides methods for reading various types of data, such as integers, doubles, strings, and booleans.
Here is an example of how you can use the Scanner
class to collect objective data from the console:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int x = scanner.nextInt(); System.out.print("Enter a double: "); double y = scanner.nextDouble(); System.out.print("Enter a string: "); String s = scanner.next(); System.out.print("Enter a boolean: "); boolean b = scanner.nextBoolean(); // use the collected data } }
This code prompts the user to enter an integer, a double, a string, and a boolean, and stores the input in variables x
, y
, s
, and b
respectively.
You can also use the Scanner
class to read data from a file by passing a File
object to the constructor. For example:
import java.io.File; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("data.txt")); // read data from the file using the same methods as above } }
In this example, the Scanner
object reads data from the file "data.txt" in the current directory.
Note that you will need to import the necessary classes and handle any exceptions that might be thrown, such as FileNotFoundException
.