The post Assign Keyboard Input to Variables in Java appeared first on OctopusCodes.
]]>You can use nextLine method to input an string value from the user and assign it to the variable.
package octopuscodes.com.demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String username;
System.out.print("username: ");
username = scanner.nextLine();
System.out.println("username from keyboard: " + username);
}
}
username: acc1
username from keyboard: acc1
You can use nextInt method to input an integer value from the user and assign it to the variable.
package octopuscodes.com.demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("id: ");
int id = scanner.nextInt();
System.out.println("id from keyboard: " + id);
}
}
id: 123
id from keyboard: 123
You can use nextFloat method to input an float value from the user and assign it to the variable.
package octopuscodes.com.demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float tempDegree;
System.out.print("tempDegree: ");
tempDegree = scanner.nextFloat();
System.out.println("tempDegree from keyboard: " + tempDegree);
}
}
tempDegree: 5.6
tempDegree from keyboard: 5.6
You can use nextDouble method to input an double value from the user and assign it to the variable.
package octopuscodes.com.demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double price;
System.out.print("price: ");
price = scanner.nextDouble();
System.out.println("price from keyboard: " + price);
}
}
price: 2567.54
price from keyboard: 2567.54
You can use nextBoolean method to input an boolean value from the user and assign it to the variable.
package octopuscodes.com.demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean status;
System.out.print("status: ");
status = scanner.nextBoolean();
System.out.println("status from keyboard: " + status);
}
}
status: true
status from keyboard: true
You can use next and charAt method to input an character value from the user and assign it to the variable.
package octopuscodes.com.demo;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char key;
System.out.print("key: ");
key = scanner.next().charAt(0);
System.out.println("key from keyboard: " + key);
}
}
key: H
key from keyboard: H
The post Assign Keyboard Input to Variables in Java appeared first on OctopusCodes.
]]>