java中读取用户输入的整数、字符、字符串、单词

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() 方法,该方法返回读取到的字符串。例如:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.println("You entered: " + str);

在这个示例中,.next 方法读取用户输入的下一个单词,并将其存储在变量 word 中。如果用户输入了多个单词,则只有第一个单词会被读取,其余的单词将保留在控制台中以待读取。

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值