java中Scanner怎么获取字符串
作者:NorthPath
时间:2023-04-29
浏览: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);
}
}
}
作者最新文章
Windows11台式机高性能模式完整配置教程
2026-10-09 09:41
贵州省住建厅与贝壳集团签署旅居战略合作:五大维度落地方案解析
2026-09-08 18:13
上海链家安住APP:业主主动卖房功能与成交数据解析
2026-09-08 18:11
如何批量将PPT转成PDF格式?PPT转PDF工具怎么选?
2026-09-04 16:03
PDF文件怎么压缩?3个小技巧帮你减小体积
2026-09-03 18:03
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多










































