java code Warm up: Variables, input, and casting (Java) (1) Prompt the user to i
ID: 3734062 • Letter: J
Question
java code
Warm up: Variables, input, and casting (Java)
(1) Prompt the user to input an integer, a double, a character, and a string, storing each into separate variables. Then, output those four values on a single line separated by a space. (Submit for 2 points).
(2) Extend to also output in reverse. (Submit for 1 point, so 3 points total).
(3) Extend to cast the double to an integer, and output that integer. (Submit for 2 points, so 5 points total).
import java.util.Scanner;
public class BasicInput {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userInt = 0;
double userDouble = 0.0;
// FIXME Define char and string variables similarly
System.out.println("Enter integer: ");
userInt = scnr.nextInt();
// FIXME (1): Finish reading other items into variables, then output the four values on a single line separated by a space
// FIXME (2): Output the four values in reverse
// FIXME (3): Cast the double to an integer, and output that integer
return;
}
}
Explanation / Answer
BasicInput.java
import java.util.Scanner;
public class BasicInput {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int userInt = 0;
double userDouble = 0.0;
System.out.print("Enter integer: ");
userInt = scan.nextInt();
System.out.print("Enter double: ");
userDouble = scan.nextDouble();
System.out.print("Enter character: ");
char charValue = scan.next().charAt(0);
System.out.print("Enter string: ");
String stringValue = scan.next();
System.out.println(userInt+" "+userDouble+" "+charValue+" "+stringValue);
System.out.println(stringValue+" "+charValue+" "+userDouble+" "+userInt);
int n = (int)userDouble;
System.out.println(userDouble+" cast to an integer is "+n);
}
}
Output:
Enter integer: 99
Enter double: 3.77
Enter character: z
Enter string: Howdy
99 3.77 z Howdy
Howdy z 3.77 99
3.77 cast to an integer is 3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.