0

Im writing code to read an integer value, maybe a float, a double, and then finally read a string. What happens is that I enter the int, press enter after which the execution should stop until I enter a string. However, as soon as I press the enter to go to a newline, I get the outout which is only the number, because execution doesnt pause for me to enter the string. Whats going on

Tried inputting number and then string, that works. Tried inputting number followed by number,that works, tried inputting several strings, that works, but i couldnt get the program to read a number and then a string.

package test;
import java.util.Scanner;
public class Trying {


        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int i = scan.nextInt();
            double d=scan.nextDouble();
            String s=scan.nextLine();
            scan.close();

            System.out.println("String: \'" + s+"\'");
            System.out.println("Double: " + d);
            System.out.println("Int: " + i);
        }
    }

I dont get an output for the string

shashgo
  • 1
  • 1

2 Answers2

1

Your problem is with using Scanner.nextLine() and Scanner.nextDouble() / Scanner.nextInt() together. You should be careful when using these together, as they might result in unexpected behavior. You can read the JavaDocs of the Scanner class for more detailed information. Instead of int i = scanner.nextInt(); double d = scanner.nextDouble(), try using double d = Double.parseDouble(scanner.nextLine()) to read in a String and convert it to a double.

1

You need to clear buffer in scanner before accepting a string input so just write

scan.nextLine();

before

String s=scan.nextLine();

and it shall work

fuzious
  • 388
  • 4
  • 18
  • yes, thank you, i should have realized that a readInt would only read an integer and not any other character. But thanks – shashgo Jul 04 '19 at 18:06
  • @shashgo in stackoverflow I guess you are a new user so here is a bit of guide for you: here you should accept the answer by clicking on the green tick below the upvotes button to close the question for a better experience for you and others,you should also comment only necessary details about the question and queries about a particular answer. Just follow few of these guidelines for a better journey on stack. Happy journey :) – fuzious Jul 09 '19 at 05:40