java中用Scanner方法如何java 读取txt每一行下一行的数据

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!
二、互相尊重,对自己的言论和行为负责。
本文标题:
本页链接:16:07 提问
JAVA,当键盘输入多行字符串时,如何停止输入。
Scanner in=new Scanner(System.in);
String[] input = new String[26];
for(int i = 0; input[i] != "end"; i++){
input[i] = in.next();
in.close();
想要达到的效果:执行程序后由键盘输入:
thisisthefistline
thisisthesecondline
结束输入,进入下一行程序。
但是事实上,即使输入了end,按下回车后,依然可以继续输入字符串和回车。
想要知道,如果我需要使这个代码停下来执行下一段代码,在for中应该用什么替换“input[i] != "end"”,以及相应的是如何停止键盘录入的?
按赞数排序
字符串不能用“=”、“!=”之类的比较。还有用for语句他是先判断后执行语句。下面代码可以实现:enter code here
Scanner in = new Scanner(System.in);
String[] input = new String[26];
int i = 0;
input[i] = in.next();
} while (!input[i - 1] .equals("end") );
in.close();
String 数组长度已经定了,暂停有错误,考虑用StringBuffier或者StringBudder
其他相似问题关于Java中Scanner.nextLine()换行的问题
今天在写Java程序时发现一个问题,代码如下:
类函数代码:
public class Player {
public void readPlayer(Scanner diskScanner) {
name = diskScanner.nextLine();
age = diskScanner.nextInt();
status = diskScanner.nextBoolean();
readPlayer函数会从一个文本文件中读取信息存入player对象中,而文本文件中的格式是这样:
主函数代码:
public static void main(String[] args) throws
IOException{
Player players[] = new Player[5];
Scanner diskScanner = new Scanner(new
File("PlayerList.txt"));
for (int num = 0; num & 5; num++) {
players[num] = new Player();
players[num].readPlayer(diskScanner);
当我debug程序时,发现当for循环执行完一次后便会报错,在调用readPlayer时,运行至diskScanner.nextInt()时出现source
not found!
经分析后,发现问题出处:当第一次执行for循环时,一切正常。但是这里有一个问题,当程序执行完status =
diskScanner.nextBoolean()后,第二个for循环开始时,Scanner光标还是停留在
true中true这一行,而nextLine()不会自动调至下一行开始扫描,而是继续扫描这一行剩下的内容(实际无内容)直到遇到换行。所以,第二个for循环的diskScanner.nextLine()执行完后其实什么都没扫描到,但是光标将被自动放入下一行,这样导致diskScanner.nextInt()直接扫描到了原本我想让diskScanner.nextLine()想扫描的内容:Jeremy(String类型),自然错误便产生了。
从Java官网上调出对Scanner.nextLine()的定义:
Advances this scanner past the current line and returns the input
that was skipped. This method returns the rest of the current line,
excluding any line separator at the
end.&The position is set
to the beginning of the next line.
Since this method continues to search through the input looking for
a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
还需要记住的是,Scanner.nextBoolean()这样的函数在扫描完后,不会将光标切换至下一行。
上述问题的解决办法:将name =
diskScanner.nextLine()换为name =
diskScanner.next()。后者会从光标处开始扫描到下一个String类型的值后停止,相比于nextLine()(遇到换行便停止),更为适用。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 java 读取txt每一行 的文章

 

随机推荐