gpt4 book ai didi

Java读入时带空格

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

我有一个简单的程序,涉及保存和读取文本文件/二维数组。问题是存储在二维数组中的字符串可能包含空格。我似乎找不到一种方法来读取/写入忽略空格但仍包含它们的文件。我可以对这两个函数进行哪些更改?

从文件中读取:

    public static void getArrayData(String [][] array){


try {
Scanner scan2 = new Scanner(new File("arrayData.txt"));


for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[i].length; j++)
{


if ( ! scan2.hasNext() )
return;

array[i][j]=scan2.next();

}


}


}

catch (FileNotFoundException e)
{
e.printStackTrace();
}

}

写入文件:

   public static void Save(String [][] array){

try {
PrintWriter writer = new PrintWriter(new File("arrayData.txt"));

for(int x=0; x<array.length; x++){
for(int y=0; y<array[x].length; y++){
writer.write(String.valueOf(array[x][y] + " "));
}
writer.println();
}

writer.flush();
writer.close();



}
catch (FileNotFoundException e)
{
e.printStackTrace();
}


}

解决方案越简单越好,因为我仍然是新手。

提前致谢

最佳答案

使用 nextLine 而不是 next 来读取整行。

array[i][j]= scan2.nextLine(); 

关于Java读入时带空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28531596/

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