java中Scanner怎么获取字符串
作者:NorthPath
时间:2023-05-03
浏览:2
1.next方法输入的有效字符后面带有空格,next()会将空格作为结束符。因此,如果输入的字符串中间部分有空格,则使用next方法是无法得到完整的字符串的。importjava.util.Scanner;publicclassTestScanner1{publicstaticvoidmain(String[]args){Scannerscan=newScanner(System.in);//从键盘接收数据System.out.println("next方式接收:");//判断是否还有输入if(scan.
本文目录
1.next 方法
输入的有效字符后面带有空格,next() 会将空格作为结束符。因此,如果输入的字符串中间部分有空格,则使用next方法是无法得到完整的字符串的。
import java.util.Scanner;
public class TestScanner1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
System.out.println("next方式接收:");
// 判断是否还有输入
if (scan.hasNext()) {
// next方式接收字符串
String str1 = scan.next();
System.out.println("输入的数据为:" + str1);
}
}
}可以看到 java 字符串并未输出。
2.nextLine方法
nextLine() 则以Enter为结束符,也就是说 ,nextLine()方法返回的是输入回车之前的所有字符。
import java.util.Scanner;
public class TestScanner2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// nextLine方式接收字符串
System.out.println("nextLine方式接收:");
// 判断是否还有输入
if (scan.hasNextLine()) {
// 从键盘接收数据
String str2 = scan.nextLine();
System.out.println("输入的数据为:" + str2);
}
}
}
作者最新文章
如何通过EMRAI助手查询EMR组件相关问题
2026-11-01 16:16
EndNote Windows版官方下载与安装教程:许可确认到Word插件验证
2026-10-30 09:21
WinRAR压缩文件教程:参数设置与分卷压缩技巧
2026-10-29 09:38
华硕5070显卡提升AI创作效率
2026-10-27 11:04
navicat怎么设置自增主键及具体操作步骤
2026-10-22 22:43
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































