2014-12-08 1 views
1

나는 주자를위한 간단한 통계 프로그램을 개발 중입니다. 한 레이스에 대해서만 데이터를 사용합니다. 내가 stackoverflow에서 도움을 후 첫 번째 부분에 대한 실행 코드가! 경기가 끝나면 주자의 이름과 시간을 입력 할 수 있습니다. 나는 그때 사람 이름을 검색하여 사람의 실행 시간을 검색하기를 바라고 있습니다 (그러면 주자 이름과 시간이 화면에 표시됩니다.) Java에서이 작업을 수행 할 수 있습니까? Thanks Cassy데이터와 관련된 이름을 입력하여 데이터 찾기

여기에 있습니다. 내 코드는 ...입니다

import java.util.Scanner; 


public class Trying 
{ 

public static void main (String[] args) 

    { 
    int num; 

    Scanner input= new Scanner (System.in); 

    System.out.println("******************************************************************* "); 
    System.out.println("Welcome to Running Race Time Statistical Analysis Application"); 
    System.out.println("******************************************************************* \n"); 


    System.out.println("Please input number of participants (2 to 10)"); 

    num=input.nextInt(); 

    // If the user enters an invalid number... display error message... 
    while(num<2|| num >10) 
    { 
     System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)..."); 

     num=input.nextInt(); 
    } 

    // declare arrays 
    double resultArray [] = new double [num]; // create result array with new operator 
    String nameArray [] = new String [num];// create name array with new operator 
    // Using the num int will ensure that the array holds the number of elements inputed by user 


    // loop to take in user input for both arrays (name and result) 
    double count = 0; 
    for (int i = 0 ; i < nameArray.length ; i++) 
     { 
      System.out.println ("Please enter a race participant Name for runner " + (i+1)); 
      nameArray[i] = input.next(); 

      System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1)); 
      resultArray[i] = input.nextDouble(); 

      count += resultArray[i]; // This count variable is used later to calculate average from total 
     } 
} 
} 
+4

예, 가능하며 코드가 광범위하게 작동합니다. 그러나이 "병렬 배열"디자인은 대신에'name'과'result' 필드를 가진'Runner' 클래스와'Runner '의 배열 (더 좋으면'List')을 가져야한다는 강력한 지표입니다. '객체. – chrylis

+0

그것의 구현을 기대하고있는 그 이름으로 함수를 검색했습니다 – CassyHiggins

+0

감사합니다 chrylis하지만 그 방법을 잘 모르겠습니다! – CassyHiggins

답변

1

그냥 사용자가 이름을 검색 할 수있게하려면, 다음이 사용

String entered; 
while(true) { 
    entered = input.nextLine(); 
    if(entered.equalsIgnoreCase("exit")) break; 
    for(int i = 0; i < nameArray.length; i++) { 
     if(entered.equals(nameArray[i])) { 
      System.out.println("Name: " + nameArray[i] + "\tTime: " + resultArray[i]); 
     } 
    } 
} 
+0

와우.그것은 훌륭하게 작동합니다. 감사! – CassyHiggins

+0

여러분을 환영합니다! – frenchDolphin

0

조회를 구현하는 가장 간단한 방법은 HashMap로입니다 또는 다른 종류의 Map입니다. m 배열보다 효율적입니다. 트릭은 모든 이름과 시간을 HashMap에 저장하는 것과 같은 코드입니다.

Map<String, Double> raceTimes = new HashMap<>(); 

for (int i = 1; i <= participants; i++) { 
    // ... some code here to enter the name and the time 

    raceTimes.put(name, time); 
} 

그것은 당신이 이름이 경우 HashMap에서 시간을 검색 한 후 쉽습니다. 코드는 다음과 같습니다.

Double time = raceTimes.get(nameEntered); 
if (time != null) { 
    System.out.println(nameEntered + " has a time of " + time); 
} 

사용자가 참가자 중 하나와 일치하지 않는 이름을 입력하는 경우 null 확인이 수행됩니다. 실제 조회는 하나의 표현 raceTimes.get(nameEntered) 일뿐입니다. 이는 두 개의 배열을 사용하는 것보다 훨씬 간단하며 원하는 값을 찾기 위해 루프를 반복합니다.

나는이 모든 것을 하나로 묶어서 완벽한 솔루션으로 만들었습니다. 당신은 내가 몇 가지 다른 것들도 바꿨음을 알 수 있습니다.

  • main이 관리하기 어려울 정도로 길어지고 있기 때문에 이것을 별도의 방법으로 분해했습니다.
  • next은 한 단어 만 읽으므로 nextLine을 사용하도록 참가자 이름에 대한 프롬프트를 변경했습니다. 이것은 참가자들이 여러 단어로 구성된 이름을 갖게합니다. 그러나이 변경과 함께 nextInt 또는 nextDouble을 호출 한 후 번호 뒤의 개행 문자를 읽지 않기 때문에 nextIntnextDouble을 호출 한 후에 nextLine에 추가 전화를 추가해야했습니다. 따라서 추가 행 번호를 읽으려면 nextLine이 필요합니다. .

전체 코드는 다음과 같습니다.

import java.util.HashMap; 
import java.util.Map; 
import java.util.Scanner; 

public class RaceTimes{ 

    public static void main(String[] args){ 
     Scanner input = new Scanner(System.in); 

     System.out.println("******************************************************************* "); 
     System.out.println("Welcome to Running Race Time Statistical Analysis Application"); 
     System.out.println("******************************************************************* \n"); 

     int participants = enterNumberOfParticipants(input); 
     Map<String, Double> raceTimes = enterTimes(input, participants); 
     lookupTimes(input, raceTimes); 
     input.close(); 
    } 

    private static int enterNumberOfParticipants(Scanner input) { 
     System.out.println("Please input number of participants (2 to 10)"); 
     int num = input.nextInt(); 

     while (num < 2 || num > 10) { 
      System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)..."); 
      num = input.nextInt(); 
     } 
     input.nextLine(); 
     return num; 
    } 

    private static Map<String, Double> enterTimes(Scanner input, int participants) { 
     Map<String, Double> raceTimes = new HashMap<>(); 

     // loop to take in user input for both arrays (name and result) 
     double totalTime = 0; 
     for (int i = 1; i <= participants; i++) { 
      System.out.println("Please enter a race participant Name for runner " + i); 
      String name = input.nextLine(); 

      System.out.println("Please enter a race result (time between 0.00 and 10.00) for runner " + i); 
      Double time = input.nextDouble(); 
      input.nextLine(); 
      totalTime += time; 

      raceTimes.put(name, time); 
     } 
     System.out.println("Average time is " + totalTime/participants); 
     return raceTimes; 
    } 

    private static void lookupTimes(Scanner input, Map<String, Double> raceTimes) { 
     while(true) { 
      System.out.println("Please enter a name that you'd like to know the time for, or type quit."); 
      String nameEntered = input.nextLine(); 
      if(nameEntered.equalsIgnoreCase("quit")) { 
       return; 
      } 
      Double time = raceTimes.get(nameEntered); 
      if (time != null) { 
       System.out.println(nameEntered + " has a time of " + time); 
      } else { 
       System.out.println("There is no participant called " + nameEntered); 
      } 
     } 
    } 
} 
관련 문제