2012-12-23 4 views
0

그래서 나는 자바를 다시 배우고있다. 기본 프로그램 (코드 주석에 설명되어 있음)을 작성하려고하는데 사용자 입력을 받아 배열에 추가하는 방법을 기억하는 데 문제가 있습니다. 나는 사용자 입력을 통해 반복하는 방법을 기억하고 아무거나 입력하면 배열에 입력을 추가 할뿐만 아니라 입력을 테스트하는 것이 더 어려워진다.사용자 입력을 받아서 배열에 추가하기

//This program will ask user for for there favorite four games 
//If the answer is blank, it will ask again for a game title 
//The program will than store there answers into an array 
//The program will than display the array in random order 
//it will then give the amount of games in the array with an integer 



import java.util.*; 

public class MultipleClassesMain { 


public static void main(String[] args) { 

    //Array holds 4 string inputs from user 
    String gameArray[] = new String[4]; 

    //importing scanner element------- 
    Scanner input = new Scanner(System.in); 

    //Introduction--------------- 
    System.out.println("Hey there!!!"); 
    System.out.println("Please tell us four game titles you like to play!!!"); 

    //Asks what game user likes and takes user input into a variable 
    System.out.println("So what a game you like?: "); 
    String temp = input.nextLine(); 

    //This loop will test against blank user input 
    while (temp.equals("") || (temp.equals(" ")){ 
     System.out.println("Your game can't be blank. Enter again: "); 

     } 

    } 

}

이것은 내가 지금까지 가지고있는 코드입니다. 누구나 사용자 입력 (입력 테스트)을 반복하고 배열에 입력을 추가하는 방법에 대한 건설적인 비판과 몇 가지 지침을 제공 할 수 있다면 크게 감사하겠습니다.

건배

답변

4

우선 대신 사용자 입력을위한 어레이의 List를 사용한다. 그냥 입력 .add(). 그러나 더 나은 해결책, 즉 Set을 사용하여 아래를보십시오.

둘째 : String에는 .trim() 메서드가 있습니다.이 메서드는 시작과 끝 모두에서 공백을 제거하고이를 사용하여 .isEmpty()을 사용하여 빈 문자열을 테스트합니다.

셋째하십시오 List 중복 항목을 감지하지 못하는, 그러나 Set는 그 항목이 올바르게 수행하는 String, equals()hashCode()을 구현하므로 다음 코드는 (이를 위해 만약 Set true를 반환의 .add() 방법 계정이 제공 않는다 조작의 결과 세트가 변경되었을 경우 만).

샘플 코드 :

public static void main(final String... args) 
{ 
    // Set of valid user inputs 
    final Set<String> gameList = new HashSet<String>(); 
    // Object from which user inputs are read 
    final Scanner in = new Scanner(System.in); 

    // Introduction 
    System.out.println("Hey there!!"); 
    System.out.println("Please tell us four game titles you like to play!!!"); 

    // What the user enters 
    String input; 

    // Check that 4 titles have been entered, don't get out of the loop until then 
    while (gameList.size() < 4) { 
     System.out.print("Enter the name of a game: "); 
     // Read one input, trim all beginning and trailing whitespaces 
     input = in.nextLine().trim(); 
     // If the resulting string is empty, input is invalid: ask for another 
     if (input.isEmpty()) { 
      System.out.println("Empty inputs not accepted!"); 
      continue; 
     } 
     if (!gameList.add(input)) 
      System.out.println("You have already selected this game (" + input + ')'); 
    } 

    // Print out the list of inputs 
    System.out.println("The list of selected games is: " + gameList); 

} 
+0

괜찮 으면이 사용 방법에 대한 예를 들어 주시겠습니까? – hijaked79

+1

편집을 참조하십시오. 그러나 여기에 추가 할 사항이 하나 더 있습니다. 중복 항목 검색. 추가됨. – fge

+0

감사합니다. 코드에 대한 의견을 보내 주셔서 감사 드리며 지금은 더 잘 이해하고 있습니다. – hijaked79

2
for (int i = 0; i < 4; i++) { 
     String temp = input.nextLine(); 
     if (temp.equals("") || (temp.equals(" "))) { 
      System.out.println("Your game can't be blank. Enter again: "); 
      i--; 
     } else 
      gameArray[i] = temp; 

    } 

이보십시오. 이게 네가 요구하는거야 .. 네?

+0

나는 그렇게 믿는다. 각 자리가 입력으로 채워지는지 확인하기 위해 목록/배열을 반복해야한다는 것을 잊어 버렸습니다. – hijaked79

관련 문제