java如何以某种方式打印数组?
所以我想在列表中打印我的数组。看起来像这样
Word: Count:
Myths 2
Of 15
Babylonia 25
我似乎不知道如何以正确的方式打印它,以下是我目前掌握的代码。感谢您的帮助,谢谢
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Program6 {
static String[] stringArray = new String[100];
static int[] intArray = new int[100];
static String fileName = "myths.txt";
static int currentWordIndex = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(fileName));
while (input.hasNext()){
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if(stringArray[i].equals(word)){
alreadyExists = true;
intArray[i]++;
break;
}
}
if(!alreadyExists && currentWordIndex <100){
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
}
}
# 1 楼答案
使用格式和循环
右对齐编辑
编辑:对其他书籍使用方法
# 2 楼答案
当你在做
它实际上是在输出的最后打印一行
尝试使用
看看这个page解释了系统的使用。printf以对齐列
# 3 楼答案
你必须正确地证明你的专栏。根据this stackoverflow question,列左对齐,前面有负号,右对齐,没有负号。你希望你的打印声明看起来像这样:
可以通过这种方式改变列宽
此外:有人提到,使用
print
而不是println
可以避免在每条语句的末尾打印一行