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);
}
}
}
作者最新文章
UC浏览器网盘下载的文件存在哪里 找不到怎么办
2026-11-20 18:18
LiteLLM v1.108.10 怎样处理异步文件请求和 Vertex AI Claude 输出上限?
2026-11-18 00:18
Yandex官网入口及最新搜索平台访问方式
2026-11-12 15:20
Yandex搜索引擎官网入口及登录教程
2026-11-12 13:54
wps office设置在哪 选项入口位置
2026-11-04 15:26
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































