如何将字符串附加到循环中的最佳值?

时间:2015-12-03 22:52:10

标签: java loops

我有一个大学的任务,我想知道是否有人可以帮助我。任务并不复杂,但我正在努力解决循环问题。

public static void main(String[] args) {
   Scanner sc =new Scanner(System.in);
    //S = Start
    //F = Finish
    //R = Race ( Final )
   byte i = 0;
   int sHours =  0,     sMinutes =  0, sSeconds = 0;
   int fHours =  0,     fMinutes =  0, fSeconds = 0;
   int sTime =   0,     fTime =     0,    rTime = 0 ; 
   int highest = 0;
   int rHours =  0,     rMinutes =  0, rSeconds = 0; 
   String name = null,  bestRunner = null;
   char gender = 0; 

    for(i = 1; i<=3; i++)
        {

        System.out.println("Please enter " + i + "runner's name");  
        name = sc.next();

        System.out.println("Please enter" + name + " runner's gender (M / F)");  
        gender = sc.next().charAt(0);

              System.out.println("Enter " + i + "'st runner's STARTING time(Seperated by space) : "); 
              sHours   = sc.nextInt(); 
              sMinutes = sc.nextInt(); 
              sSeconds = sc.nextInt(); 

              System.out.println("Enter " + i + "'st runner's FINISHING time hours: "); 
              fHours   = sc.nextInt(); 
              fMinutes = sc.nextInt(); 
              fSeconds = sc.nextInt(); 

              //Converting to seconds
              sTime = ((sHours*3600)+(sMinutes*60)+sSeconds); 
              fTime = ((fHours*3600)+(fMinutes*60)+fSeconds); 
              rTime = ((fTime - sTime)); 
              //Best time recording to loop
              if (i == 1 || rTime < highest){ 
                  highest = rTime;  
                  bestRunner = name;  
              } 
        }



        System.out.println("Name\t\tGender\t\tStart Time    \tFinish time\t\tRACE TIME"); 
        System.out.println(name + gender + rTime);

       sc.close();
}

}

好的,我的问题在于:

if (i == 1 || rTime < highest){ 
    highest = rTime;  
    bestRunner = name;  
}

我想记录我输入的跑步者的最佳时间,并且在输出线中我想要显示最佳时间和跑步者名字。 (我稍后会处理性别问题) 问题是它总是记录最后一个循环输入,而不是最低输入。

这个问题可能会被问到,但我仍然无法弄清楚这个问题是什么。

1 个答案:

答案 0 :(得分:3)

您已在[{1}}中保存了您关注的名称,但您打印出bestRunnernamehighest

也是如此
rTime

应该是:

System.out.println(name + gender + rTime);