gpt4 book ai didi

java - {} 格式不同?格式化困境

转载 作者:行者123 更新时间:2023-12-01 12:00:08 26 4
gpt4 key购买 nike

所以我有这个代码并打印它:

import java.util.*;

public class Reverse_Copy {

public static void main(String[] args){

//create an array and covert to list
Character[] ray = {'p','w','n'};
List<Character> l = new ArrayList<Character>(Arrays.asList(ray));
System.out.println("List is: ");
output(l);

//reverse and print out the list
Collections.reverse(l);
System.out.println("After reverse: ");
output(l);

//create a new array and a new list
Character[] newray = new Character[3];
List<Character> listCopy = new ArrayList<Character>(Arrays.asList(newray));

//copy contens of list l into list listCopy
Collections.copy(listCopy, l);
System.out.println("Copy of list: ");
output(listCopy);

//fill collection with crap
Collections.fill(l,'X');
System.out.println("After filling the list: ");
output(l);

}

private static void output(List<Character> thelist){

for(Character thing: thelist)
System.out.printf("%s ", thing);
System.out.println();


}

}

这是打印:

List is: 
p w n
After reverse:
n w p
Copy of list:
n w p

这与 enhanced for loops 的括号中的代码相同。 .

    import java.util.*;

public class Reverse_Copy {

public static void main(String[] args){

//create an array and covert to list
Character[] ray = {'p','w','n'};
List<Character> l = new ArrayList<Character>(Arrays.asList(ray));
System.out.println("List is: ");
output(l);

//reverse and print out the list
Collections.reverse(l);
System.out.println("After reverse: ");
output(l);

//create a new array and a new list
Character[] newray = new Character[3];
List<Character> listCopy = new ArrayList<Character>(Arrays.asList(newray));

//copy contens of list l into list listCopy
Collections.copy(listCopy, l);
System.out.println("Copy of list: ");
output(listCopy);

//fill collection with crap
Collections.fill(l,'X');
System.out.println("After filling the list: ");
output(l);

}

private static void output(List<Character> thelist){

for(Character thing: thelist){
System.out.printf("%s ", thing);
System.out.println();
}

}

}

这是打印内容:

List is: 
p
w
n
After reverse:
n
w
p
Copy of list:
n
w
p
After filling the list:
X
X
X

我觉得这很奇怪,简单的括号与打印方式有什么关系?对于为什么会发生这种情况有什么想法吗?如果你不相信我,你可以自己测试一下。我找不到发生这种情况的任何理由。非常奇怪。

<小时/>

编辑:重复网站中的答案仅证明它不会改变任何内容。证明添加花括号如何改变事物而不是保持不变。

最佳答案

当您省略 for 循环中的括号时,仅执行第一行:

 for(Character thing: thelist)
System.out.printf("%s ", thing);
System.out.println();

它将对 thelist 中的每个元素执行 printf 行,然后仅执行一次 println 。不要让缩进欺骗了你。

还有

 for(Character thing: thelist){
System.out.printf("%s ", thing);
System.out.println();
}

它将针对 thelist 中的每个元素执行 printf 行和 println 行。

关于java - {} 格式不同?格式化困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036754/

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