0

I am just try to get a input as float but, I got an error. Please, help me to fix it.

This is my code

import java.util.Scanner;
public class {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        
        // Input
        int a = in.nextInt();  // Integer
        String b = in.nextLine();  // String
        Float c = in.nextFloat();  // Float
        
        // Output
        System.out.println("Given integer :"+a);
        System.out.println("Given string :"+b);
        System.out.println("Given Float :"+c);
    }
}

This is Output

2 
stack 
Exception in thread "main" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:864) 
    at java.util.Scanner.next(Scanner.java:1485) 
    at java.util.Scanner.nextFloat(Scanner.java:2345) 
    at Main.main(Main.java:9)
Naman
  • 23,555
  • 22
  • 173
  • 290

3 Answers3

1

If you want to have any whitespace character as a seperator just use next() for reading a String:

// Input
int a = in.nextInt();  // Integer
String b = in.next();  // String
float c = in.nextFloat();  // float

This will accept all input values in one line or with line breaks

123 abc 456.789
Given integer :123
Given string :abc
Given Float :456.789

or

123
abc
456.789
Given integer :123
Given string :abc
Given Float :456.789

If you aim to have only line breaks as input separator use the solution suggested by @marc:

// Input
int a = in.nextInt();  // Integer
in.nextLine();
String b = in.nextLine();  // String
float c = in.nextFloat();  // float

output will be:

123
abc
456.789
Given integer :123
Given string :abc
Given Float :456.789

and consequent expressions in the same line will be ignored:

123 abc 4.5
def
6.7
Given integer :123
Given string :def
Given Float :6.7
Hakan Dilek
  • 2,024
  • 2
  • 21
  • 30
0

nextInt() does not read the new line character (when you click return). You need an additional nextLine() Try with:

int a = in.nextInt();  // Integer
in.nextLine();
String b = in.nextLine();  // String
Float c = in.nextFloat();  // Float
Marc
  • 1,749
  • 1
  • 7
  • 18
0

javadoc of nextline says

Advances this scanner past the current line and returns the inputthat was skipped.This >method returns the rest of the current line, excluding any lineseparator at the end. The >position is set to the beginning of the nextline. Since this method continues to search through the input lookingfor a line separator, it >may buffer all of the input searching forthe line to skip if no line separators are >present.

Advancing the line causes that in.nextFloat tries to read and parse "stack". This will become visible if you write only numbers in the console

i recommend to read strings with next() instead of nextLine()