我正在处理一个以升序或降序打印位置数组的代码。但是,对于12个位置中的两个位置,格式都是错误的。
代码:
import java.util.*;
import static java.lang.System.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
class airwaysReservation {
static Scanner sc = new Scanner(System.in);
static String src[] = {"Mumbai", "London", "Hiroshima", "Lagos", "Minsk", "Baghdad", "Istanbul", "Delhi", "Fez", "Beijing", "Taipei", "Havana"};
static String dest[] = {"Hyderabad", "Paris", "Athens", "Alexandria", "Seoul", "Hamburg", "Bengaluru", "Rome", "Montreal", "Saitama", "Philadelphia", "Pune"};
public static void sortAsc(String arr[]) {
Arrays.sort(arr);
}
public static void sortDesc(String arr[]) {
//using libraries java.util.Arrays, and java.util.Collections, sorts arrays
Arrays.sort(arr, Collections.reverseOrder());
}
public static void list() {
out.println("Sources \t Destinations");
for (int i = 0; i< 12; i++) {
out.println(src[i] + "\t \t " + dest[i]);
}
}
public static void main(String[] args) {
out.println("Welcome \n Would you like to see the sources in ascending, or descending order?");
// stores ascending or descending for later
char schoice = sc.next().charAt(0);
out.println("Would you like to view the destinations in ascending, or descending order?");
// stores ascending or descending for later
char dchoice = sc.next().charAt(0);
switch (schoice) {
case 'a' :
sortAsc(src);
break;
case 'd' :
sortDesc(src);
break;
default:
out.println("Invalid choice");
}
switch (dchoice) {
case 'a' :
sortAsc(dest);
break;
case 'd' :
sortDesc(dest);
break;
default:
out.println("Invalid choice");
}
list();
}
}
为此选择的输出,升序然后降序为:
Sources Destinations
Baghdad Seoul
Beijing Saitama
Delhi Rome
Fez Pune
Havana Philadelphia
Hiroshima Paris
Istanbul Montreal
Lagos Hyderabad
London Hamburg
Minsk Bengaluru
Mumbai Athens
Taipei Alexandria
我觉得这个问题是由于单词长度不同而引起的,但是这似乎并不影响最后几行(例如明斯克和班加罗尔)。 如何使所有目的地都从同一垂直线开始? 任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
注意,它仅影响第一个单词为8个字符或更多的行。 \t
前进到下一个标签位置,该位置通常为8个字符的倍数。
要正确执行此操作,必须先遍历第一个单词以找到最大长度,然后在打印时使用该长度在每个单词后插入正确数量的空格。
例如,如果您确定最长的第一个单词是13个字符,并且想让第二个单词以偏移量16(位置17)开头,则可以在长度为16的固定字段中打印第一个单词。
答案 1 :(得分:0)
您尝试过String.format("%-12s %-12s", source, destination)
吗?这将为每个字符串分配12个字符,但是如果您觉得需要更多字符,请继续进行更改,并根据需要更改每个12
。
这是我尝试演示的内容:
public static void main(String[] args) {
String [][] arr = {
{ "Sources", "Destinations" },
{ "Baghdad", "Seoul" },
{ "Beijing", "Saitama" },
{ "Delhi", "Rome" },
{ "Fez", "Pune" },
{ "Havana", "Philadelphia" },
{ "Hiroshima", "Paris" },
{ "Istanbul", "Montreal" },
{ "Lagos", "Hyderabad" },
{ "London", "Hamburg" },
{ "Minsk", "Bengaluru" },
{ "Mumbai", "Athens" },
{ "Taipei", "Alexandria" }
};
for (String[] a : arr) {
System.out.printf("%-12s %-12s \n", a[0], a[1]);
}
}
获取输出:
Sources Destinations
Baghdad Seoul
Beijing Saitama
Delhi Rome
Fez Pune
Havana Philadelphia
Hiroshima Paris
Istanbul Montreal
Lagos Hyderabad
London Hamburg
Minsk Bengaluru
Mumbai Athens
Taipei Alexandria