1

I have an assignment where we have to make a Java program that will read 4 inputs from the user:

  • Integer
  • Double
  • Character
  • String

Then it outputs them in the above order in one line, and in reverse order in another line.

The inputs are

  • Integer: 99
  • Double: 3.77
  • Character: z
  • String: Howdy

However when they are outputted, the String is just blank

Expected results:

Enter integer: 
Enter double: 
Enter character: 
Enter string: 
99 3.77 z Howdy
Howdy z 3.77 99
3.77 cast to an integer is 3

Actual results:

Enter integer: 
Enter double: 
Enter character: 
Enter string: 
99 3.77 z 
 z 3.77 99
3.77 cast to an integer is 3

Here is the code that I have

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
      char myChar;
      String myString = "";
      
      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
      System.out.println("Enter double: ");
      userDouble = scnr.nextDouble();
      
      System.out.println("Enter character: ");
      myChar = scnr.next().charAt(0);
      
      System.out.println("Enter string: ");
      myString = scnr.nextLine();
      
      
      System.out.println(userInt + " " + userDouble + " " + myChar + " " + myString);
   
      // FIXME (2): Output the four values in reverse
      System.out.println(myString + " " + myChar + " " + userDouble + " " + userInt);
      
      // FIXME (3): Cast the double to an integer, and output that integer
      System.out.println(userDouble + " cast to an integer is " + (int)userDouble);
      
      return;
   }
}

How do I get the String to show in the output? It is just displaying as an empty string. I've even tried to initialize the myString variable to "Hello", but it still displays empty.

  • 1
    I would bet it is the same problem as in this question: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) -- that is, `nextLine()` is reading (up to) the newline from previous input (`next()` which does not *consume* the newline from the input) || Solution: add a `dummy* call to `nextLine()` before reading the string – user22471702 Sep 01 '23 at 16:44
  • 3
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Sören Sep 01 '23 at 17:05

5 Answers5

2

The following should work.

You can request the input on the same line using System.out.print and you can use String.format to output the variables. Don't forget to close the Scanner!

Note: When grabbing partial string input, you need to call scanner.nextLine() to dump the buffer, before requesting more string values.

import java.util.Scanner;

public class BasicInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Inputs
        int userInt;
        double userDouble;
        char myChar;
        String myString;

        System.out.print("Enter integer: ");
        userInt = scanner.nextInt();

        System.out.print("Enter double: ");
        userDouble = scanner.nextDouble();

        System.out.print("Enter character: ");
        myChar = scanner.next().charAt(0);

        scanner.nextLine(); // Clear the buffer

        System.out.print("Enter string: ");
        myString = scanner.nextLine();

        // Output the four values in order
        System.out.printf("%d %.2f %s %s%n", userInt, userDouble, myChar, myString);

        // Output the four values in reverse order
        System.out.printf("%s %s %.2f %d%n", myString, myChar, userDouble, userInt);

        // Cast the double to an integer, and output that integer
        System.out.println(userDouble + " cast to an integer is " + (int) userDouble);

        scanner.close();
    }
}

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

If you want to take all the inputs at once, you can do the following:

import java.util.Scanner;

public class BasicInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Inputs
        int userInt;
        double userDouble;
        char myChar;
        String myString;

        System.out.print("Enter an integer, double, character, and a string: ");

        userInt = scanner.nextInt();
        userDouble = scanner.nextDouble();
        myChar = scanner.next(".").charAt(0); // See: https://stackoverflow.com/a/13942707/1762224
        myString = scanner.nextLine().trim();

        // Output the four values in order
        System.out.printf("%d %.2f %s %s%n", userInt, userDouble, myChar, myString);

        // Output the four values in reverse order
        System.out.printf("%s %s %.2f %d%n", myString, myChar, userDouble, userInt);

        // Cast the double to an integer, and output that integer
        System.out.println(userDouble + " cast to an integer is " + (int) userDouble);

        scanner.close();
    }
}

Output

Enter an integer, double, character, and a string: 99 3.77 z Howdy
99 3.77 z Howdy
Howdy z 3.77 99
3.77 cast to an integer is 3

If you want to be strict about which charcter can be entered, you can use a pattern:

myChar = scanner.next("[A-Za-z]").charAt(0); // Only alpha
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • _Don't forget to close the Scanner!_ Not if it wraps `System.in`. In any case it will be closed when the JVM terminates, besides which, in the code in your question, closing the `Scanner` is the last thing that your code does so it's kind of moot, anyway. – Abra Sep 02 '23 at 04:10
0

Check out this answer

Basically, it boils down to the scanner can be a bit "finicky" when you use certain commands like "next" instead of "nextline" If I recall when I would use Java I would usually just scan with nextline and then cast after the fact

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • Maybe you could post some code demonstrating what you mean and how it relates to the code in the question. – Abra Sep 02 '23 at 04:27
0

we should clear/flush the scanner to remove any residual buffer left in the input buffer.

In you case, you input a character for myChar and then you ENTER so it will suppose that myString = scnr.nextLine(); will be an ENTER because the ENTER be know as the buffer after this input.

myChar = scnr.next().charAt(0);

For example: when it's go to input for myChar, you type: "c Howdy" and ENTER, so it will know that myChar = 'c' and myString will be "Howdy ENTER".

Therefore, we have clear the Scanner to ensure that there are no extra characters/tokens left in the previous input. In java, when you use Scanner next(), nextInt(), or nextLine() it after leaves the newline character '\n'/

To clear the Scanner buffer, you can use this

Scanner.nextLine();

Based on your code, you should use this after input for myChar:

scnr.nextLine();

Your full of code should like this

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
        char myChar;
        String myString = "";
        
        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
        System.out.println("Enter double: ");
        userDouble = scnr.nextDouble();
        
        System.out.println("Enter character: ");
        myChar = scnr.next().charAt(0);
        scnr.nextLine(); // clear buffer
        
        System.out.println("Enter string: ");
        myString = scnr.nextLine();
        
        
        System.out.println(userInt + " " + userDouble + " " + myChar + " " + myString);
        
        // FIXME (2): Output the four values in reverse
        System.out.println(myString + " " + myChar + " " + userDouble + " " + userInt);
        
        // FIXME (3): Cast the double to an integer, and output that integer
        System.out.println(userDouble + " cast to an integer is " + (int)userDouble);
        return;
    }
}
ldn
  • 82
  • 3
0

"... when they are outputted, the String is just blank ..."

"... How do I get the String to show in the output? It is just displaying as an empty string. I've even tried to initialize the myString variable to "Hello", but it still displays empty."

If you're looking to read input one line at a time, use the Scanner#nextLine method.
The next methods, nextInt, nextDouble, etc., are used for obtaining values within a single-line.

System.out.println("Enter integer: ");
userInt = Integer.parseInt(scnr.nextLine());

// FIXME (1): Finish reading other items into variables, then output the four values on a single line separated by a space
System.out.println("Enter double: ");
userDouble = Double.parseDouble(scnr.nextLine());

System.out.println("Enter character: ");
myChar = scnr.nextLine().charAt(0);

System.out.println("Enter string: ");
myString = scnr.nextLine();

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

Here is an example demonstrating how to read the 4 values when written on one line.
I've added the String#stripLeading to remove any white-space characters.

Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
double b = scanner.nextDouble();
char c = scanner.next().charAt(0);
String d = scanner.nextLine().stripLeading();
System.out.printf("%s %s %s %s%n%4$s %3$s %2$s %1$s", a, b, c, d);

Output

99 3.77 z Howdy
99 3.77 z Howdy
Howdy z 3.77 99
Reilas
  • 3,297
  • 2
  • 4
  • 17
0

Just another alternative. It only utilizes the Scanner#nextLine() method and makes use of the String#matches() method to carry out input validation for each prompt. If a prompt input validation fails, the User is permitted to try again. The User can also quit on any prompt. Be sure to read the comments in code:

public class BasicInput {
    
    // OS related newline character sequence:
    public final String LS = System.lineSeparator();
    
    // The JVM will automatically close this resource when the application ends.
    private final java.util.Scanner scnr = new java.util.Scanner(System.in);
    
    private int userInt;
    private double userDouble;
    private char myChar;
    private String myString = "";
        

    public static void main(String[] args) {
        /* App started this way to avoid the need 
           for statics (unless we want them):  */
        new BasicInput().startApp(args);
    }
    
    private void startApp(String[] args) {
        /* List Interface of Object - Will hold the values of the 
           above variables once they are filled.               */
        java.util.List<Object> list = new java.util.ArrayList<>();
        
        System.out.println("Enter 'q' to quit at any time:" + LS);
        
        // PROMPT #1 - Enter Integer Value:
        String intNum = "";
        while (intNum.isEmpty()) {
            System.out.print("Enter an integer value: -> ");
            intNum = scnr.nextLine().trim(); // Trim off leading/trailing spaces (if any):
            
            // Is quit desired?
            if (intNum.equalsIgnoreCase("q")) {
                quit();
            }
            
            /* VALIDATE USER ENTRY:     
               If the supplied string is NOT (!) a representation of a signed 
               or unsigned integer value which is within Integer.MIN_VALUE
               and Integer.MAX_VALUE then, inform the User and allow him 
               or her to try again:                                   */
            if (!intNum.matches("-?\\d+") || new java.math.BigInteger(intNum).longValue() < Integer.MIN_VALUE 
                                          || new java.math.BigInteger(intNum).longValue() > Integer.MAX_VALUE) {
                System.out.println("Invalid Numerical Integer (int type) Entry! (" + intNum + ") Try again..." + LS);
                intNum = "";
            }
        }
        
        // Fill `userInt` member variable - Convert String to int:
        userInt = Integer.parseInt(intNum);
        // Add to List
        list.add(userInt);  
        
        
        // PROMPT #2 - Enter Floating Point (double type) Value:
        String dblNum = "";
        while (dblNum.isEmpty()) {
            System.out.print("Enter a floating point value: -> ");
            dblNum = scnr.nextLine().trim(); // Trim off leading/trailing spaces (if any):
            
            // Is quit desired?
            if (dblNum.equalsIgnoreCase("q")) {
                quit();
            }
            
            /* VALIDATE USER ENTRY:     
               If the supplied string is not a representation of a signed 
               or unsigned integer or floating point value then, inform
               the User and allow him/her to try again:              */
            if (!dblNum.matches("-?\\d+(\\.\\d+)?")) {
                System.out.println("Invalid Numerical Floating-Point Entry! (" 
                                   + dblNum + ") Try again..." + LS);
                dblNum = "";
            }
        }

        // Fill `userDouble` member variable - Convert String to double:
        userDouble = Double.parseDouble(dblNum);
        // Add to List:
        list.add(userDouble);
        
        
        // PROMPT #3 - Enter A Specific Character:
        String charVal = "";
        while (charVal.isEmpty()) {
            System.out.print("Enter a specific character (one only and no spaces): -> ");
            charVal = scnr.nextLine().trim(); // Trim off leading/trailing spaces (if any):
            
            // Is quit desired?
            if (charVal.equalsIgnoreCase("q")) {
                quit();
            }
            
            /* VALIDATION - If nothing or just one or more white-spaces (tabs, etc) 
               are supplied then re-loop:           */
            if (charVal.isEmpty()) {
                System.out.print("Invalid Entry! You must supply a keyboard character!" + LS);
            }
        }
        
        // Fill `myChar` member variable - Get first character (only) from User's entry:
        myChar = charVal.charAt(0);
        // Add to List:
        list.add(myChar);
        

        // PROMPT #4 - Enter A Specific String:
        String strgVal = "";
        while (strgVal.isEmpty()) {
            System.out.print("Enter any specific string (not just spaces): -> ");
            strgVal = scnr.nextLine().trim();
            
            // Is quit desired?
            if (strgVal.equalsIgnoreCase("q")) {
                quit();
            }
            
            /* VALIDATION - If nothing or just one or more white-spaces (tabs, etc) 
               are supplied then re-loop:           */
            if (strgVal.isEmpty()) {
                System.out.print("Invalid Entry! Your string must contain something!" + LS);
            }
        }

        // Fill `myString` member variable:
        myString = strgVal;
        // Add to List:
        list.add(myString);

        
        // Display Listed Values, Forward:
        System.out.println(LS + "Forward:  " + list.stream().map(Object::toString)
                           .collect(java.util.stream.Collectors.joining(" ")));

        // Display Listed values, Reversed
        java.util.Collections.reverse(list); // Reverse the elements in List
        System.out.println("Reverse:  " + list.stream().map(Object::toString)
                           .collect(java.util.stream.Collectors.joining(" ")));

        
        // Cast the double to an integer, and output that integer
        System.out.println("Double " + userDouble + " cast to an integer is: " + (int) userDouble);
    }

    private void quit() {
        System.out.println(LS + "Quiting - Bye Bye");
        System.exit(0);
    }
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22