nextInt() 方法是 Java 中 Scanner 类的一个方法,用于从输入流中读取下一个整数。它不能直接读取字符串。如果你想要读取字符串,可以使用 nextLine() 方法。
下面是一个简单的示例,展示了如何使用 nextInt() 和 nextLine() 方法:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("你输入的整数是:" + number);
// 读取换行符之前的内容,即字符串
scanner.nextLine();
System.out.print("请输入一个字符串:");
String text = scanner.nextLine();
System.out.println("你输入的字符串是:" + text);
scanner.close();
}
}
在这个示例中,我们首先使用 nextInt() 方法读取一个整数,然后使用 nextLine() 方法读取换行符之前的内容(即字符串)。注意,在读取整数后,我们需要调用 nextLine() 方法来消费掉换行符,否则下一次调用 nextLine() 时将直接读取到换行符,而不是用户输入的字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1198875.html