In Java please.
Write a code that prompts 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. The output to be look like:
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
1. Below is the code that is giving error, please provide the correct code for above requirement.
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
String randomcharacter = " ";
String enterstring = " ";
Character randomc = ' ';
System.out.println("Enter integer: ");
userInt = scnr.nextInt();
System.out.println("Enter double: ");
userDouble = scnr.nextDouble();
System.out.println("Enter character: ");
randomcharacter = scnr.nextLine();
randomc = randomcharacter.charAt(0);
System.out.println("Enter string: ");
enterstring = scnr.next();
System.out.println(userInt + " " + userDouble + " " + randomc + " " + enterstring);
System.out.println(enterstring + " " + randomc + " " + userDouble + " " + userInt);

Respuesta :

ijeggs

Answer:

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;

       String randomcharacter;

       String enterstring ;

       char randomc;

       System.out.println("Enter integer: ");

       userInt = scnr.nextInt();

       System.out.println("Enter double: ");

       userDouble = scnr.nextDouble();

       System.out.println("Enter character: ");

       randomcharacter = scnr.nextLine();

       randomc = scnr.nextLine().charAt(0);

       System.out.println("Enter string: ");

       enterstring = scnr.next();

       System.out.println(userInt + " " + userDouble + " " + randomc + " " + enterstring);

       System.out.println(enterstring + " " + randomc + " " + userDouble + " " + userInt);

       System.out.println(userDouble+" cast to an it is "+(int)userDouble);

   }

}

Explanation:

  • Two changes was made to the code to give the required output see them boldened
  • Firstly the declarion is chabged from Character to char
  • Then an output line is added to print teh value of the userDouble casted to an int