Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Classes Used for Input and Conversion in Java
Wrapper Classes / Methods
These methods all take an argument of type String and return a number of the conversion type.
Integer.parseInt()
Float.parseFloat()
Double.parseDouble()
//class Integer, method parseInt()
//class Float, method parseFloat()
//class Double, method parseDouble()
These methods are useful when getting input using a JOptionPane dialog box. The input will be a String
so if what you need it to be is a number you must convert it.
int number;
String numberString;
numberString
number
=
=
Scanner Class
JOptionPane.showInputDialog("Enter a number");
Integer.parseInt(numberString);
(
Must import
java.util.Scanner )
Use the Scanner class to create an input object that can be used to get input from the user interactively
(console input), input from a data file, or even input from a String.
Scanner Class Methods
next()
nextLine()
nextInt()
nextFloat()
nextDouble()
//get
//get
//get
//get
//get
hasNext()
//returns true if some type of input exists, false otherwise
hasNextInt(), hasNextDouble(), hasNextFloat()
a String
rest of line as a String
an integer
a float number
a double number
Use the Scanner class to create an input object to get console input:
// Create Scanner object to get user input from the console (keyboard)
Scanner input = new Scanner(System.in);
int number;
System.out.print("Enter an integer: ");
number = input.nextInt();
Use the Scanner class to create an input object to get input from a file:
// Create Scanner object to get input from a data file
Scanner inFile = new Scanner(new File(“myFile.txt”));
double itemPrice;
String itemDescription;
if (inFile.hasNext()) // If there is still data in the file…
{
itemPrice = inFile.nextDouble( ); // get a double value and store it in itemPrice
itemDescription = inFile.nextLine( );
// get a string and store it in itemDescription
}