gpt4 book ai didi

JAVA - 如何从扫描仪读取文件中检测到 "\n"字符

转载 作者:行者123 更新时间:2023-12-01 23:01:43 25 4
gpt4 key购买 nike

第一次发海报,

我在读取文本文件的扫描仪中读取返回字符时遇到问题。

正在读取的文本文件如下所示:

//test.txt start//

2

0 30 30 1

1 90 30 0

//test.txt end//

第一行:2(表示两个点)

第二行:位置索引:0 xpos:30 ypos:30 绘制线到位置 1

第三行:位置索引:1 xpos: 90 ypos: 30 绘制线到位置 0

我知道代码更改应该放在这个 do/while 中。

do {        
edge[pNum].add(input.nextInt());
} while(input.hasNextInt());

代码的其余部分似乎按预期运行,但我似乎无法检测到文本文件中的 "\n" 返回字符,以便将 x,y 值保存在位置数组和 ArrayList 中的以下值,并对文本文件中的下一行重新开始该过程。

完整代码如下:

public class PointReader extends JFrame {

class GraphView extends JPanel{

}

public static void main(String[] args) throws Exception{

String fileName;

System.out.print("Input File Name: ");
Scanner user = new Scanner( System.in );
fileName = user.nextLine();

java.io.File file = new java.io.File(fileName);

Scanner input = new Scanner(file);

int count = input.nextInt();

int[][] position = new int[count][2];
ArrayList[] edge = new ArrayList[count];

for(int k = 0; k < edge.length; k++){
edge[k] = new ArrayList<Integer>();
}

while(input.hasNextInt()){

int pNum = input.nextInt();
int xPos = input.nextInt();
int yPos = input.nextInt();

position[pNum][0] = xPos;
position[pNum][1] = yPos;

do{
edge[pNum].add(input.nextInt());
}while(input.hasNextInt());
}

System.out.println(count);

for(int i=0; i < count; i++){
System.out.println(i + " " + position[i][0] + " " + position[i][1] + " ");

for(int j = 0; j < edge[i].size(); j++){
System.out.print(edge[i].get(j) + " ");
}
}
}
}

我已经尝试了 while(!(input.next().equals("\n"))); 但仍然没有被检测到。有任何想法吗?

最佳答案

如果您想将文件分成几行,最简单的方法可能是单独处理每一行。

while (input.hasNextLine())
{
String line = input.nextLine();

// DO STUFF WITH LINE...
}

因此,您可以将每一行放入字符串“line”中,然后可以用它做一些事情,并且您不必自己负责分隔行。但除此之外,我不能百分百确定您要做什么。

关于JAVA - 如何从扫描仪读取文件中检测到 "\n"字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23312161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com