2017-01-05 1 views
1

사용자 입력 (결과 일치)을 한 줄에 입력하고 입력을 분할하여 동일한 데이터를 다른 형식으로 출력하는 작은 프로젝트를 진행하고 있습니다. 나는 특정 형식으로 데이터를 출력하는 방법을 찾기 위해 고심하고있다. 뿐만 아니라 게임 플레이 횟수 합계로, 나는 내 프로그램 형식으로 출력 같은 차트를 생성 할특정 레이아웃의 콘솔로 어떻게 출력합니까?

home_name [home_score] | away_name [away_score] 

이 내가 다음과 같은 형식

라인 후 입력 결과 라인에 사용자를 허용하는 순간에이 코드입니다
home_name : away_name : home_score : away_score 

stop을 입력 할 때까지 루프가 중단됩니다 (데이터가 출력되기를 바랍니다).

import java.util.*; 
public class results { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     int totalGames = 0; 
     String input = null; 
     System.out.println("Please enter results in the following format" 
       + " home_name : away_name : home_score : away_score" 
       + ", or enter stop to quit"); 

     while (null != (input = scan.nextLine())){ 
      if ("stop".equals(input)){ 
       break; 
      } 
      String results[] = input.split(" : "); 
      for (int x = 0; x < results.length; x++) { 

      }  
     totalGames++; 
     } 
     System.out.println("Total games played is " + totalGames); 
    } 
} 
+0

[요다 조건 (https://en.wikipedia.org/wiki/Yoda_conditions)하여 while 루프가 사용 . 그 이유가 뭐야? –

+0

구체적인 이유가 없습니다. 어쩌면 제가 가르친 스타일 만 받았습니다. 'while ((input = scan.nextLine())! = "stop")'은 단순화하는 것처럼 보인다. – user7379397

+0

'=='또는'! = '연산자를 사용하여 문자열을 비교하지 마십시오. 대신 'equals'을 사용해야합니다. 예를 들어, 'while ((input = ...)! = null &&! input.equals ("stop"))' –

답변

2

here을 볼 수 있습니다.

원하는대로 텍스트 서식을 지정할 수 있습니다.

일반 구문은 % [arg_index $으로 [플래그] [폭]. 정밀] 변환 인수 문자 번호 (0이 아닌 1)에서 시작한다. 첫 번째 인수를 인쇄하려면 에 1 $를 사용해야합니다 (명시 적 순서를 사용하는 경우).

0

results 배열 값을 finalResults ArrayList에 추가하여 게임 통계를 유지할 수 있습니다. 그런 다음 그 결과를 stop 입력으로 입력합니다.
팀당 총 결과를 계산하려면 HashMap<String, Integer>이 최선의 선택입니다.

import java.util.*; 

// following the naming conventions class name must start with a capital letter 
public class Results { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     int totalGames = 0; 
     String input; 
     System.out.println("Please enter results in the following format: \n" 
       + "'HOME_NAME : AWAY_NAME : HOME_SCORE : AWAY_SCORE' \n" 
       + "or enter 'stop' to quit"); 

     // HashMap to keep team name as a key and its total score as value 
     Map<String, Integer> scoreMap = new HashMap<>(); 
     // ArrayList for storing game history 
     List<String> finalResults = new ArrayList<>(); 
     // don't compare null to value. Read more http://stackoverflow.com/questions/6883646/obj-null-vs-null-obj 
     while ((input = scan.nextLine()) != null) { 
      if (input.equalsIgnoreCase("stop")) { // 'Stop', 'STOP' and 'stop' are all OK 
       scan.close(); // close Scanner object 
       break; 
      } 
      String[] results = input.split(" : "); 

      // add result as String.format. Read more https://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/ 
      finalResults.add(String.format("%s [%s] | %s [%s]", results[0], results[2], results[1], results[3])); 

      // check if the map already contains the team 
      // results[0] and results[1] are team names, results[2] and results[3] are their scores 
      for (int i = 0; i < 2; i++) { 
       // here is used the Ternary operator. Read more http://alvinalexander.com/java/edu/pj/pj010018 
       scoreMap.put(results[i], !scoreMap.containsKey(results[i]) ? 
         Integer.valueOf(results[i + 2]) : 
         Integer.valueOf(scoreMap.get(results[i]) + Integer.valueOf(results[i + 2]))); 
      } 
      totalGames++; // increment totalGames 
     } 

     System.out.printf("%nTotal games played: %d.%n", totalGames); // output the total played games 

     // output the games statistics from ArrayList finalResults 
     for (String finalResult : finalResults) { 
      System.out.println(finalResult); 
     } 

     // output the score table from HashMap scoreMap 
     System.out.println("\nScore table:"); 
     for (Map.Entry<String, Integer> score : scoreMap.entrySet()) { 
      System.out.println(score.getKey() + " : " + score.getValue()); 
     } 
    } 
} 

지금 입력을 테스트 : 여기

는 명확하게하기 위해 주석이있는 전체 코드입니다

team1 : team2 : 1 : 0 
team3 : team1 : 3 : 2 
team3 : team2 : 2 : 2 
sToP 

출력은 다음과 같습니다

Total games played: 3. 

team1 [1] | team2 [0] 
team3 [3] | team1 [2] 
team3 [2] | team2 [2] 

Score table: 
team3 : 5 
team1 : 3 
team2 : 2 
+0

네, 그 형식이 완벽합니다! 그러나 나는 루프가 깨진 후 예를 들어, 사용자가 3 행의 결과를 입력했다고 가정하고 그 형식으로 모든 결과를 출력 할 수있는 방법을 고민하고있다. 이것은 루프를 깨고, 오직 그때 그 형식으로 데이터가 서로 아래에 출력되고 싶습니다. – user7379397

+0

내 대답을 업데이트했습니다. 다시 시도하십시오. – DimaSan

+0

간단하고 완벽하게 작동합니다, 감사합니다! – user7379397

1

당신은 정규식을 사용할 수 있습니다 줄을 구문 분석 :

(\ w) \ S (\ w) \ s의 | \ s의 (\ w) \의 사용

import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

    public class MatcherFindStartEndExample{ 

     public static void main(String[] args){ 

      String text = "Belenenses 6 | Benfica 0"; 

      String patternString = "(\\w+)\\s(\\w+)\\s\\|\\s(\\w+)\\s(\\w+)"; 

      Pattern pattern = Pattern.compile(patternString); 
      Matcher matcher = pattern.matcher(text); 


      while (matcher.find()){ 
        System.out.println("found: " + matcher.group(1)); 
        System.out.println("found: " + matcher.group(2)); 
        System.out.println("found: " + matcher.group(3)); 
        System.out.println("found: " + matcher.group(4)); 
      } 
     }} 

에서 (http://tutorials.jenkov.com/java-regex/matcher.html에서) 자바 코드에

자료 (\ w)이 코드 대신 당신의

String results[] = input.split(" : "); 
      for (int x = 0; x < results.length; x++) { 

      } 
0

의 당신은 두 번에 일을해야합니다

1) 사용자가 입력 한 정보를 검색하고 사용자 정의 클래스의 인스턴스에 저장 : PlayerResult합니다.

2) 예상 된 포맷에 따라 출력을 수행. 또한 그래픽 테이블을 만들기 전에 각 열의 최대 크기를 계산해야합니다.
그렇지 않으면 추악한 렌더링이 될 수 있습니다.

첫번째 단계 :

List<PlayerResult> playerResults = new ArrayList<PlayerResult>(); 

... 
String[4] results = input.split(" : "); 
playerResults.add(new PlayerResult(results[0],results[1],results[2],results[3]) 

번째 단계 : 제쳐두고

// compute length of column 
int[] lengthByColumn = computeLengthByColumn(results); 
int lengthHomeColumn = lengthByColumn[0]; 
int lengthAwayColumn = lengthByColumn[1]; 

// render header 
System.out.print(adjustLength("home_name [home_score]", lengthHomeColumn)); 
System.out.println(adjustLength("away_name [away_score]", lengthAwayColumn)); 

// render data 
for (PlayerResult playerResult : playerResults){ 
    System.out.print(adjustLength(playerResult.getHomeName() + "[" + playerResult.getHomeName() + "]", lengthHomeColumn)); 
    System.out.println(adjustLength(playerResult.getAwayName() + "[" + playerResult.getAwayScore() + "]", lengthAwayColumn)); 
} 
관련 문제