1、取用户输入的整数
如果你想从控制台读取整数,可以使用 .nextInt()方法:例如:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);
这段代码向用户询问输入一个数字,并使用 .nextInt()
方法读取该数字。该方法读取用户输入,并将其作为整数返回,然后存储在变量 number
中。
2、取用户输入的字符
如果你想从控制台读取字符,可以使用 next().charAt(0)
方法:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char character = scanner.next().charAt(0);
System.out.println("You entered: " + character);
在这个示例中,.next()
方法读取用户输入,并将其作为字符串返回。然后,使用 .charAt(0)
方法从字符串中读取第一个字符,并将其存储在变量 character
中。
3、取用户输入的字符串
如果你想从控制台读取字符串,可以使用 nextLine()
方法:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.println("You entered: " + str);
在这个示例中,.nextLine()
方法读取用户输入的一整行字符串,并将其存储在变量 str
中。
4、取用户输入的单词
如果你想从控制台读取单词(一个由空格分隔的字符串),可以使用 .next()
方法,该方法返回读取到的字符串。例如:文章来源:https://www.toymoban.com/news/detail-461166.html
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.println("You entered: " + str);
在这个示例中,.next
方法读取用户输入的下一个单词,并将其存储在变量 word
中。如果用户输入了多个单词,则只有第一个单词会被读取,其余的单词将保留在控制台中以待读取。文章来源地址https://www.toymoban.com/news/detail-461166.html
到了这里,关于java中读取用户输入的整数、字符、字符串、单词的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!