2014-12-05 4 views
2

미친 libs 템플릿을 작성하고 컴퓨터가 빈칸을 채우는 Mad Libs 프로그램을 만들고 싶습니다. 지금까지이있어 :텍스트 파일에서 무작위 라인을 반환

package madlibs; 
import java.io.*; 
import java.util.Scanner; 

/** 
* 
* @author Tim 
*/ 
public class Madlibs { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) throws IOException { 
    File nouns = new File("nounList.txt"); 
    Scanner scan = new Scanner(nouns); 
    while(scan.hasNextLine()){ 
     if("__(N)".equals(scan.nextLine().trim())){ 
      int word = (int) (Math.random() * 100); 

     } 
    } 
} 

} 

nounList.txt 파일은 별도의 행에 명사의 목록, 각이 포함되어 있습니다. 질문 : Math.random 함수를 사용하여 어떤 행을 사용할지 어떻게 선택합니까?

+2

플랫 파일의 무작위 액세스가 좋지 않습니다. 선택하면 전체 파일을 읽고 무작위로 하나를 선택하거나 무작위로 선택된 색인에 도달 할 때까지 줄 단위로 읽는 것입니다. 대신 데이터베이스를 사용하는 것이 좋습니다. sqlite를 고려하십시오. – Andreas

답변

1

목록에있는 모든 명사를 가져온 다음 목록에서 임의의 요소를 선택하십시오.

예 : 내가 본 의견 중 하나에 의해 제안 내가 다른 접근 방식을 만들 것

// Nouns would contain the list of nouns from the txt file 
List<String> nouns = new ArrayList<>(); 
Random r = new Random(); 
String randomNoun = nouns.get(r.nextInt(0, nouns.length)); 
+1

파일이 거대한 경우 어떻게해야합니까? 더 좋은 해결책은 랜덤 액세스를 사용하는 것입니다. –

+0

455 단어가 있습니다 – Tim

+0

455 단어 만 잘됩니다. – MCMastery

0

이 접근하지 않고, 그것을 할 수있는 또 다른 방법이 될 것입니다

try { 
     //I would prefer to read my file using NIO, which is faster 
     Path pathToMyTextFile = Paths.get("nounList.txt"); 
     //Then I would like to obtain the lines in Array, also I could have them available for process later 
     List<String> linesInFile = Files.readAllLines(pathToMyTextFile, StandardCharsets.ISO_8859_1); 
     //If I want to access a random element, I would use random methods to access a random index of the list and retrieve that element 
     Random randomUtil = new Random(); 

     //I will use the formula for random and define the maximum (which will be the length of the array -1) and the minimum which will be zero 
     //since the indexes are represented from 0 to length - 1 
     int max = linesInFile.size() - 1; 
     int min = 0; 

     //You can simplify this formula later, I'm just putting the whole thing 
     int randomIndexForWord = randomUtil.nextInt((max - min + 1)) + min; 

     //Here I get a random Noun 
     String randomWord = linesInFile.get(randomIndexForWord); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

명사가 필요할 때마다

감사하고 ... 행복 코딩 : 두 가지 주요 작업이 있습니다

0

:

는 명사의 모든 읽기가

// Open the file 
    File file = new File("MyFile.txt"); 

    // Attach a scanner to the file 
    Scanner fin = new Scanner(file); 

    // Read the nouns from the file 
    ArrayList<String> nouns = new ArrayList<>(); 
    while (fin.hasNext()) { 
     nouns.add(fin.next()); 
    } 

임의

에서 하나를 선택
// Pick one at random 
    int randomIndex = (int)(Math.random() * nouns.size()); 
    String randomNoun = nouns.get(randomIndex); 

    // Output the result 
    System.out.println(randomNoun); 

예를 들어, 명사가 10 개일 경우 Math.random() * 10은 0.0-9.999 ... 9의 범위를 나타냅니다. int 형으로 캐스팅하면 소수점이 자르며 0에서 9 사이의 균등 배분을 유지합니다.

기술적으로 완벽한 10.0을 굴릴 수 있으며 프로그램이 IndexOutOfBoundsException으로 중단됩니다. 통계적으로 이런 일이 발생하는 것은 불가능하지만, 통계적으로 불가능한 것은 코드로는 충분하지 않습니다. 10.0을 굴리는 경우를 처리하는 논리를 추가하는 것을 고려하십시오.

관련 문제