首页 > 解决方案 > 如何连接号码和姓名?

问题描述

所以程序应该询问三个跑步者的姓名和完成时间,并按数字顺序打印时间和姓名。现在它只是打印数字。我如何连接它们?因为我无法连接字符串和整数?当我尝试将一个或另一个设置为 String 和 int 时,它在 if 部分中不起作用。

import java.util.scanner;
public class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        int a;
        int b;
        int c;
        String name1;
        String name2;
        String name3;
        char repeat = 0;

        do {
            System.out.println("Enter the name of the first runner:");
            name1 = keyboard.nextLine();

            System.out.println("Enter the finishing time:");
            a = keyboard.nextInt();
            keyboard.nextLine();

            System.out.println("Enter the name of a second runner:");
            name2 = keyboard.nextLine();

            System.out.println("Enter the finishing time:");
            b = keyboard.nextInt();
            keyboard.nextLine();

            System.out.println("Enter the name of a third runner");
            name3 = keyboard.nextLine();

            System.out.println("Enter the finishing time");
            c = keyboard.nextInt();

            //The problem should be solved here?

            int min;
            int max;
            int med;

            if (a > b) {
                if (a > c) {
                    max = a;
                    if (b > c) {
                        med = b;
                        min = c;
                    } else {
                        med = c;
                        min = b;
                    }
                } else {
                    med = a;
                    max = c;
                    min = b;
                }
            } else {
                if (b > c) {
                    max = b;
                    if (a > c) {
                        med = a;
                        min = c;
                    } else {
                        med = c;
                        min = a;
                    }
                } else {
                    med = b;
                    max = c;
                    min = a;
                }
            }

            System.out.println(min);
            System.out.println(med);
            System.out.println(max);
        } while (repeat == 'Y' || repeat == 'y');
    }
}

标签: java

解决方案


更好的方法是有一个带有两个字段的 Player 类,

    class Player implements Comparator
    {
      String name;
      int timeTaken;
      //add getter and setter
      // most importantly override Equal, hashcode and compare
    

      @Override
      public int compare(Object o1, Object o2) {
        //compare them with timeTaken
      }
    }

现在在你的主程序中,一旦你得到输入,你应该创建播放器对象并将其存储在一个TreeSet

只需打印您的树集,它将根据 timeTaken 进行排序。


推荐阅读