Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2.29 Warm up: Variables, input, and casting (Java) in ZyBooks (1) Prompt the use

ID: 3879355 • Letter: 2

Question

2.29 Warm up: Variables, input, and casting (Java) in ZyBooks

(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).

Here is the given java code:

import java.util.Scanner;

public class BasicInput {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userInt;
double userDouble;
// 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
}
}

Explanation / Answer

Program

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;
char userChar='a';
String userString="abcde";
// FIXME Define char and string variables similarly

System.out.println("Enter integer: ");//Read integer
userInt = scnr.nextInt();
System.out.println("Enter double: ");//Read double
userDouble = scnr.nextDouble();
System.out.println("Enter character: ");//Read Character
userChar=scnr.next().charAt(0);
System.out.println("Enter string: ");//Read String
userString=scnr.next();
// FIXME (1): Finish reading other items into variables, then output the four values on a single line separated by a space
System.out.println("Input: "+userInt+" "+userDouble+" "+userChar+" "+userString);
// FIXME (2): Output the four values in reverse
System.out.println("Reverse: "+userString+" "+userChar+" "+userDouble+" "+userInt);
// FIXME (3): Cast the double to an integer, and output that integer
System.out.println("Double to Integer: "+(int)userDouble);
return;
}
}

Output