打印特定字符

时间:2017-10-10 07:21:24

标签: java string for-loop input char

我有一个字符串输入,该输入的团队名称和分数由一个空格分隔。例如bb 3teamd 5获胜者应为teamd

为了获得得分最高的获胜者团队,我正在做以下事情:

Scanner scanner = new Scanner(System.in);
    int cases = scanner.nextInt();

    printWinnerTeam(cases);



}

public static void printWinnerTeam(int cases) {
    Scanner scanner = new Scanner(System.in);
    String str = "";
    String winnerTeam = "";
    int winnerScore = 0, countedChar = 0;

    for (int i = 0; i < cases; i++) {
        str += scanner.nextLine();
    }
    char[] arr = str.toCharArray();
    for (int i = 0; i < arr.length; i++) {
        countedChar++;
        if (arr[i] == ' ') {
            if (str.charAt(i + 1) > winnerScore) {
                winnerTeam = "";
                winnerScore = (int) str.charAt((int) i + 1);
                for (int j = 0; j < countedChar; j++) {
                    winnerTeam += str.charAt(j);
                }
                countedChar = 0;
            } else {
                //winnerTeam = "";
                countedChar = 0;
            }
        }
    }
    System.out.println(winnerTeam);
}

但它不是完美的工作,它打印有线结果,如何按预期工作?

2 个答案:

答案 0 :(得分:0)

我还没有尝试过你的代码,但我想象一个大问题是str += scanner.nextLine();的连接新行将直接附加到前一行的末尾

看看这个

    Scanner sc = new Scanner(System.in);
    int bestScore = Integer.MIN_VALUE;
    String team = "Nothing entered";
    System.out.println("how many teams");
    int count = sc.nextInt();
    sc.nextLine();
    while (count-- > 0) {
        System.out.println("Entered team,score");

        String line = sc.nextLine();
        String arr [] = line.split(" ");
        // check size - TBD
        if (Integer.parseInt(arr[1]) > bestScore) {
            bestScore = Integer.parseInt(arr[1]);
            team = arr[0];
        }
    }

    System.out.println("nest team is " + team + " with a score of " + bestScore);

答案 1 :(得分:0)

如果我必须这样做,我会这样做:

@Entity
@Table(name = "USER_DETAILS")
public class UserDetail {

  @Id
  @Column(nullable = false)
  private UUID id;

  @OneToMany
  @JoinColumn(name = "USER_ID", referencedColumnName = "ID")
  private List<User> users;

  @Column(nullable = false)
  private boolean married;

  public User getUser() {
    return users.stream().reduce((a, b) -> {
      if (a.getLastModified().isAfter(b.getLastModified())) {
        return a;
      }
      return b;
    }).orElseThrow(() -> new IllegalStateException("User detail is detached from a User."));
  }

  // Constructors, Getter, Setter, ...

}