2013-04-12 2 views
13

배열의 가격 목록과 함께 가격 목록을 표시하고 가격을 정렬하고 싶습니다. 나는 거의 작동하지만 개선이 필요하다. 아래는 코드와 출력입니다. 모든 가격을 어떻게 조정할 수 있습니까? 지금까지는 일부 작업을하지만 일부 작업은 수행하지 않습니다. 미리 감사드립니다.Java에서 printf 출력을 정렬하십시오.

//for loop 
System.out.printf("%d. %s \t\t $%.2f\n", 
       i + 1, BOOK_TYPE[i], COST[i]); 

출력 :

1. Newspaper   $1.00 
2. Paper Back  $7.50 
3. Hardcover book  $10.00 
4. Electronic book  $2.00 
5. Magazine   $3.00 
+0

http://docs.oracle.com/javase/7/docs/api/java /util/Formatter.html은 출력을 정렬하는 방법을 보여줍니다. 예를 들면 다음과 같습니다. formatter.format (Locale.FRANCE, "e = % + 10.4f", Math.E); 여기서 10은 등호와 인쇄되는 숫자 사이의 "공백"수이고 4는 소수 자릿수입니다. –

답변

16

아래의 예를 시도해 볼 수 있습니다. 왼쪽 들여 쓰기를 확인하려면 너비 앞에 '-'를 사용하십시오. 기본적으로 오른쪽 들여 쓰기됩니다. 이는 귀하의 목적에 부합하지 않을 수 있습니다.

System.out.printf("%2d. %-20s $%.2f%n", i + 1, BOOK_TYPE[i], COST[i]); 

형식 문자열 구문 : http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

포맷 숫자 인쇄 출력 : https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS :이 DWB의 대답에 주석으로 갈 수있는,하지만 난 아직 언급 할 수있는 권한이 그렇게하지 않습니다 답변.

3

떠오르는 간단한 솔루션 공간의 String 블록 가지고있다 : 문자열을 인쇄 할 때

String indent = "     "; // 20 spaces. 

가 실제 들여 계산 및 끝까지 추가 :

String output = "Newspaper"; 
output += indent.substring(0, indent.length - output.length); 

문자열의 공백 수를 조정하여 모두 같은 열에 배치합니다.

+0

이런 대답을 보면 Java의'String'에 다른 프로그래밍 언어의 표준 라이브러리처럼'padLeft','padRight' 등이 있었으면합니다 ... – Patashu

+1

Java에는 StringUtils.leftPad()와 StringUtils.rightPad()가 있습니다. 이것들은 Apache Commons Lang의 일부입니다. – DwB

6

printf 및 printf와 같은 형식의 형식 사양은 선택적 width 매개 변수를 사용합니다.

System.out.printf("%10d. %25s $%25.2f\n", 
        i + 1, BOOK_TYPE[i], COST[i]); 

너비를 원하는 값으로 조정하십시오.

+8

먼저, 그 사람에 대해 알지 못하면 게으른 사람에게 전화하지 마십시오. 둘째, 저는 자바 초보자입니다 만 printf에 관해 읽었고 % 10d가 변수 앞에 10 칸을 인쇄한다는 것을 알고 있습니다. Mr. Know-it-all-and-not-lazy는 코드가 내가 필요한 곳에 가까이 있지 않습니다. 내 질문을 읽으면 두 번째 변수를 변경해야하는 공간 (상수가 아님)을 제외하고 세 번째 변수도 정렬됩니다.어쨌든 고마워. 좋은 날. – user1781482

+1

만약 당신이 printf 문서를 읽었다면 % 10d는 10의 필드 너비를 지정하고 % 010d는 너비가 0 인 패딩 된 왼쪽 필드를 지정한다는 것을 알 것입니다. – DwB

+1

문서를 읽으면 플래그로 필드가 왼쪽으로 정렬됩니다. ex % -10d – DwB

1

가장 긴 bookTypes 값을 기준으로 bookType 열의 너비 (즉, bookTypes 값의 형식)를 으로 설정하는 잠재적 인 해결책이 있습니다.

public class Test { 
    public static void main(String[] args) { 
     String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" }; 
     double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 }; 

     // Find length of longest bookTypes value. 
     int maxLengthItem = 0; 
     boolean firstValue = true; 
     for (String bookType : bookTypes) { 
      maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length()); 
      firstValue = false; 
     } 

     // Display rows of data 
     for (int i = 0; i < bookTypes.length; i++) { 
      // Use %6.2 instead of %.2 so that decimals line up, assuming max 
      // book cost of $999.99. Change 6 to a different number if max cost 
      // is different 
      String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n"; 
      System.out.printf(format, i + 1, bookTypes[i], costs[i]); 
     } 
    } 
} 
0

당신은 콘솔에 인쇄 포맷 컬러 텍스트에 대한이 블로그를 참조 할 수 있습니다

https://javaforqa.wordpress.com/java-print-coloured-table-on-console/

public class ColourConsoleDemo { 
/** 
* 
* @param args 
* 
* "\033[0m BLACK" will colour the whole line 
* 
* "\033[37m WHITE\033[0m" will colour only WHITE. 
* For colour while Opening --> "\033[37m" and closing --> "\033[0m" 
* 
* 
*/ 
public static void main(String[] args) { 
// TODO code application logic here 
System.out.println("\033[0m BLACK"); 
System.out.println("\033[31m RED"); 
System.out.println("\033[32m GREEN"); 
System.out.println("\033[33m YELLOW"); 
System.out.println("\033[34m BLUE"); 
System.out.println("\033[35m MAGENTA"); 
System.out.println("\033[36m CYAN"); 
System.out.println("\033[37m WHITE\033[0m"); 

//printing the results 
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n"; 

System.out.format("|---------Test Cases with Steps Summary -------------|%n"); 
System.out.format("+----------------------+---------+---------+---------+%n"); 
System.out.format("| Test Cases   |Passed |Failed |Skipped |%n"); 
System.out.format("+----------------------+---------+---------+---------+%n"); 

String formattedMessage = "TEST_01".trim(); 

leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n"; 
System.out.print("\033[31m"); // Open print red 
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0); 
System.out.print("\033[0m"); // Close print red 
System.out.format("+----------------------+---------+---------+---------+%n"); 
} 
관련 문제