我无法从 java 中的浮动用户那里获得输入

I can't get a input from user as float in java

我只是想将输入作为浮点数获取,但出现错误。请帮我解决一下。

这是我的代码

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);
    }
}

这是输出

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)

nextInt() 不读取新行字符(当您单击 return 时)。您需要一个额外的 nextLine() 试试:

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

下一行的 javadoc 说

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.

推进该行会导致 in.nextFloat 尝试读取和解析“堆栈”。 如果您在控制台中只写数字,这将变得可见

我建议使用 next() 而不是 nextLine() 读取字符串

如果你想用任何空白字符作为分隔符,只需使用 next() 来读取 String:

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

这将在一行中或使用换行符接受所有输入值

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

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

如果您打算只使用换行符作为输入分隔符,请使用@marc 建议的解决方案:

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

输出将是:

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

以及同一行中的后续表达式将被忽略:

123 abc 4.5
def
6.7
Given integer :123
Given string :def
Given Float :6.7