![](/img/trans.png)
[英]Read file of objects and write it back to a new one a single character at a time
[英]How to read in multiple characters from a file, multiply the character into a grid and print back to a new file
我試圖從文件中讀取多個字符乘以每個字符,以便當我將其打印到新文件時,它們以網格格式顯示。
int num = 4;
String fileStr = "";
scnrIn.useDelimiter("zzzzzzzzz");
while(scnrIn.hasNextLine()) {
fileStr = scnrIn.nextLine();
char[] charArray = fileStr.toCharArray();
for(int i = 0; i < charArray.length; ++i) {
for(int j = 0; j < Math.sqrt(num); ++j) {
writer.write(charArray[i]);
for(int k = 1; k < Math.sqrt(num); ++k) {
writer.write(charArray[i]);
}
writer.newLine();
writer.flush();
}
}
}
}
}
如果我的txt文件包含@#$和我的mulitplier為4的字符,我希望打印新的txt文件:
@@##$$
@@##$$
但相反,我得到:
@@
@@
##
##
$$
$$
我覺得這個問題與writer.newLine()有關; 但是如果我拿走它或將其評論出去,它就不會在網格中打印出來。 我不知道如何解決在網格中打印新行的需要。
您的問題與for循環的嵌套有關。 如果您按照代碼所做的操作,就會在網格中寫出i
中的一個當前字符,然后轉到charArray
的下一個字符。
相反,您應該做的是按行並在轉到新行之前打印出每個字符的當前字符列數。 這主要需要切換兩個最外部的for循環,然后修復你寫入的頻率。
這是代碼按預期工作:
int num = 4;
int cols = (int) Math.sqrt(num); //easier to read the code when stored in a variable
int rows = cols;
String fileStr = "";
scnrIn.useDelimiter("zzzzzzzzz");
while(scnrIn.hasNextLine()) {
fileStr = scnrIn.nextLine();
char[] charArray = fileStr.toCharArray();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < charArray.length; j++) {
char curChar = charArray[j]; //this is the current character we want to write out for the number of columns times
for (int k = 0; k < cols; k++) {
writer.write(curChar);
}
}
writer.newLine(); //create a new line after every row
}
writer.flush(); //better to only flush output when fully done
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.