2012-06-06 18 views
0

다음 코드는 jgrasp에서 컴파일되지만 You null null을 읽습니다. 텍스트 파일을 읽고 배열에 저장하는 방법을 알아낼 수 없습니까?배열에 텍스트 파일을 읽는 중

import java.io.*; 
import java.util.Scanner; 
import java.util.Random; 
public class InsultGenerator { 

//randomly picks an adjective and a noun from a list of 10 random nouns and adjectives 
//it then creates a random insult using one adjective and one noun 
public static void main (String [] args)throws IOException 
{ 
    String[]adjectives = new String [10]; 
    String[]nouns = new String [10]; 
    int size = readFileIntoArray (adjectives); 
    int size2 = readFileIntoArray2 (nouns); 
     String adjective = getAdjective(adjectives, size); 
    String noun = getNoun(nouns, size2); 
    printResults(adjectives, nouns, adjective, noun); 
} 

public static int readFileIntoArray (String[] adjectives)throws IOException 
{ 
    Scanner fileScan= new Scanner("adjectives.txt"); 
    int count = 0; 
    while (fileScan.hasNext()) 
    { 
     adjectives[count]=fileScan.nextLine(); 
     count++; 
    } 
    return count; 
} 
public static int readFileIntoArray2(String[] nouns)throws IOException 
{ 
    Scanner fileScan= new Scanner("nouns.txt"); 
    int count = 0; 

    while (fileScan.hasNextLine()) 
    { 
     nouns[count]=fileScan.nextLine(); 
     count++; 
    } 
    return count; 
} 
public static String getAdjective(String [] adjectives, int size) 
{ 
    Random random = new Random(); 
    String adjective = ""; 
    int count=0; 
    while (count < size) 
    { 
     adjective = adjectives[random.nextInt(count)]; 
     count ++; 
    } 
    return adjective; 
} 
public static String getNoun(String[] nouns, int size2) 
{ 
    Random random = new Random(); 
    String noun = ""; 
    int count=0; 
    while (count < size2) 
    { 
     noun = nouns[random.nextInt(count)]; 
     count ++; 
    } 
    return noun; 
} 
public static void printResults(String[] adjectives, String[] nouns, String adjective, String noun) 
{ 
    System.out.println("You " + adjective + " " + noun); 
} 
} 

교사는 run 인수를 사용하여 각 텍스트 파일을 거기에 넣기를 원합니다. 따라서 실행 결과는 adjectives.txt, nouns.txt (각 파일은 10 개의 명사 또는 형용사의 목록입니다)이라고 나와 있습니다.
배열에 저장 한 다음 각 목록에서 무작위로 하나를 선택하고 문을 작성하는 프로그램을 가져 오려고합니다.

답변

1

new Scanner(new File("adjectives.txt"))을 사용해야합니다. 또한 명령 인수를 사용해야하므로 사용하십시오! 문자열의 파일 이름 및 반환 배열을 쓰기 방법 :

public String[] readLines(String filename) throws IOException { 
    String[] lines = new String[10]; 
    Scanner fileScan= new Scanner(new FIle(filename)); 
    // read lines 
    // ... 
    return lines; 
} 

당신이 방법 readFileIntoArray(2) 거의 동일한 2가 없어도이 방법.

0

다른 답변에서 언급했듯이 스캐너에 올바른 구문을 사용하십시오.

또한 getNoun() 및 getAdjective() 메소드를 확인하십시오. 나는 그들이 예상 결과를 내는지 확신하지 못한다. 그리고 만약 그렇다면, 그들은 다소 복잡해 보인다. 이런 식으로 뭔가를 시도 :

public static String getString(String[] str) {  
    Random rand = new Random(); 

    String retVal = str[rand.nextInt(str.length)]; 

    return retVal; 
} 

자바 배열은 크기가 length 변수 인스턴스에 저장합니다. nextInt(int upperBound)도 상한이 필요합니다.

관련 문제