gpt4 book ai didi

java - 尝试打印转置字符串[]

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

所以我一直在尝试获取一个包含这样输入的 txt 文件,例如 -

abcddhdj
efghdd
ijkl

得到这个 -

j
d
hd
dd
dhl
cgk
bfj
aei

我尝试使用 2d char 数组来做到这一点,它给出了 nullException 和 arrayoutofbound 错误,并且大部分不起作用,然后尝试了 string array 、 arraylist of arraylist of char ,最后我一直在尝试使用 string 的 arraylsit

这是我使用 string[] 进行大量搜索后得到的最接近的解决方案 -

public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")); // PUT YOUR FILE LOCATION HERE
int k=0,i,j=0,x;
String line[] = new String[10] ; //SET THE APPROXIMATE NUMBER OF ROWS
while((line[k] = br.readLine()) !=null)
{System.out.println(line[k]); //print to check input - verified
k++;


}
for(x=0;x<k;x++)
{if(j<line[x].length())
{j=line[x].length()-1;} //this part not working in above loop
}
System.out.println(j); // verified but not working inside previous loop for some reason
System.out.println(k);


for(x=j-1;x>=0;x++) //without this loop,its perfect, but with it gives indexoutofbound error , doesnt run at x=j
{ for(i=0;i<k;i++)
{ System.out.print(line[i].charAt(x));
}
System.out.println();
}

}

这是一个输出

run:
abcd
efgh
ijkl
4 //should have come as 3 since i did length-1
3
chl //notice the d missing , every char of first row shifted,just why
bgk //in outofbound error , it only prints d at the end, need explanation
afj
ei
BUILD SUCCESSFUL (total time: 0 seconds)

如果我在 abcd 之后添加一个空格,它会给出 indexoutofbound 并且在 k 之后没有输出最后我使用了另一种方法,它添加空格以使所有长度相等但输出还是错误,而且这种思维方式有问题,应该有更好的方法

所以我尝试了 arraylist ,这又给我带来了更多问题

尝试通过任何可以理解的方法来解决这个问题。

最佳答案

这应该可以解决问题:

这里的关键是我用空字符填充所有行数组,以便每个字符数组的长度与最长行的长度相同。

public static void main(String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")))
{
String line;
List<List<Character>> lines = new ArrayList<>();

int longestLine = 0;
while((line = br.readLine()) !=null)
{
line = line.trim();

if (line.length() > 0)
{
List<Character> currList = new ArrayList<>();
for (char c : line.toCharArray())
{
currList.add(c);
}

if (currList.size() > longestLine)
{
longestLine = currList.size();
}

lines.add(currList);
}
}

// pad all lists to be the same as the longest
for (List<Character> currList : lines)
{
while (currList.size() < longestLine)
{
currList.add(Character.MIN_VALUE);
}
}

// go through each list backwards
for (int i = longestLine - 1; i >= 0; i-- )
{
for (List<Character> currList : lines)
{
System.out.print(currList.get(i));
}
System.out.println();
}
}
catch (Throwable t)
{
t.printStackTrace();
}
}

输入示例:

abcd
efgh
ijkl
g

示例输出:

dhl
cgk
bfj
aeig

关于java - 尝试打印转置字符串[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40118945/

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