我是Java新手,仍然对扫描仪next方法的实际工作方式感到困惑。这里有一个示例程序:
import java.util.Scanner;
public class HelloJava{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int varInt;
String varString;
String varStringTwo;
System.out.print("Insert int value: ");
varInt = sc.nextInt();
System.out.print("Insert string value: ");
varString = sc.nextLine();
System.out.print("Insert another string value: ");
varStringTwo = sc.nextLine();
sc.close();
}
}
当我执行程序并在第一个提示符中输入一个整数时,终端看起来像这样:
Insert int value: 15
Insert string value: Insert another string value: // i can input any value here //
// ^ but the program doesn't allow me to input anything here
我知道其中一个解决方案是把"sc.nextLine();"between varInt = "sc. nexint ();"one_answers"System.out.print("Insert a string value: ");",但我不明白为什么或如何。
当您用空格扫描String
值时,scanner.next()
方法将为您提供字符串到空格。
例如,
您的输入是This is a String
因此,当您第一次运行scanner.next()
时,它将返回值This
。如果您再次运行它,它将返回is
等。