How to Read a Text File in Java and Store It in an Array

9 Replies - 75083 Views - Last Post: 06 April 2010 - 04:twoscore PM Rate Topic: - - - - -

#1

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 14
  • Joined: 25-March ten

reading text file storing it into an assortment

Posted 04 Apr 2010 - 01:53 PM

import java.io.*; import java.util.Scanner; import java.util.Random;  public class InsultGenerator  {  //randomly picks an describing word and a noun from a list of 10 random nouns and adjectives //it then creates a random insult using ane adjective and one noun  	public static void main (Cord [] args)throws IOException  	{ 		String[]adjectives = new Cord [x]; 		String[]nouns = new String [10]; 		int size = readFileIntoArray (adjectives); 		int size2 = readFileIntoArray2 (nouns); 	        String adjective = getAdjective(adjectives, size); 		String substantive = getNoun(nouns, size2); 		printResults(adjectives, nouns, adjective, substantive );  		 	}  	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 describing word = ""; 		int count=0; 		while (count < size) 		{ 			adjective = adjectives[random.nextInt(count)];  			count ++; 		} 		return adjective; 	}  	public static String getNoun(Cord[] 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(Cord[] adjectives, String[] nouns, Cord adjective, String noun) 	 	 	 	{ 	Organisation.out.println("Yous " + adjective + " " + noun); 	 	}  }                

It does compile in jgrasp but it reads out You nothing nothing. I tin can't figure out how to get my text files to read and store into their arrays. The teacher wants us to employ run argument and put each text file in there. so my run argument says adjectives.txt nouns.txt. Each of those files is a list of ten nouns or adjectives. I want to store them into arrays then get the programme to randomly option one from each list and make a statement. I take everything in the way that I have been shown and then far as I don't know much. This is my first java form so any help would exist appreciated. Thanks.


Is This A Skillful Question/Topic? 0

  • +

Replies To: reading text file storing it into an array

#ii m-e-g-a-z User is offline

Reputation: 497

  • View blog
  • Posts: one,457
  • Joined: xix-October 09

Re: reading text file storing it into an array

Posted 04 April 2010 - 02:34 PM

You should create and Instantiate a File object and use information technology with the Scanner Object y'all have created. I believe this is why you lot are having problems with reading the file.

Likewise, what i propose, is to use an ArrayList because that way yous will not have to worry well-nigh the size of the array.

Heres a quick exmaple i mocked upwardly

import coffee.io.File; import java.io.FileNotFoundException; import java.util.*; public class case {  	//Static Scanner and File Objects 	static Scanner s;  	static File f; 	// Static method that returns an ArrayList 	static ArrayList<String> words (Scanner s, File f){ 		//Instantiate File with file name within parameters 		f = new File("test.txt"); 		//Instantiate Scanner s with f variable within parameters 		//surround with effort and catch to see whether the file was read or not 		try { 			s = new Scanner(f); 		} grab (FileNotFoundException due east) {  			e.printStackTrace(); 		} 		//Instantiate a new ArrayList of String type 		ArrayList <Cord> theWord = new ArrayList <String>(); 		//while it has next .. 		while(s.hasNext()){ 			//Initialise str with word read 			Cord str=s.next(); 			//add to ArrayList 			theWord.add(str);  		} 		//return ArrayList 		render theWord;  	}  	public static void main (Cord [] args){ 		//Initialise new ArrayList 		ArrayList <Cord> fileWords; 		//Assign returned arraylist with fileWords 		fileWords=words(s,f); 		//Print 		Arrangement.out.println(fileWords);  	} }                

If you cant utilize an ArrayList, the example above will give you lot a crude idea of how to convert it into an Assortment.


#3 MadScientist305 User is offline

  • New D.I.C Caput

Reputation: 6

  • View blog
  • Posts: 44
  • Joined: 26-December 09

Re: reading text file storing it into an array

Posted 04 Apr 2010 - 02:35 PM

You are not using the Scanner constructor correctly. To take the scanner objects read from a file, you need to pass the constructor a File object. It would look something similar this:

Scanner myFileScanner = new Scanner(new File("myfile.txt"));                

As well, your calls to the Random object's nextInt() method should throw an IllegalArgumentException since you are passing count as a parameter and count is initially 0(nextInt() expect a positive number to be passed).


#4 carden2 User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 14
  • Joined: 25-March x

Re: reading text file storing it into an assortment

Posted 04 April 2010 - 06:11 PM

View Postm-due east-g-a-z, on 04 April 2010 - 01:34 PM, said:

If yous deceit use an ArrayList, the instance above volition give yous a rough thought of how to convert information technology into an Array.

this seems mode over my head. i tried to piece of work with what you showed me and information technology returned like 35 errors. I know the teacher wants me to utilize the filescan like i have it that what our worksheet shows that we were given to aid us with this program.

View PostMadScientist305, on 04 April 2010 - 01:35 PM, said:

You are not using the Scanner constructor correctly. To take the scanner objects read from a file, you need to pass the constructor a File object. It would wait something similar this:

Scanner myFileScanner = new Scanner(new File("myfile.txt"));                  

As well, your calls to the Random object's nextInt() method should throw an IllegalArgumentException since y'all are passing count as a parameter and count is initially 0(nextInt() expect a positive number to be passed).

yah i dont know the code in my box does compile. i did work on changing it so now it does take new file in there and now im working on count. i still don't understand why information technology wont read my file in though and just says null 10 times for my list.


#v MadScientist305 User is offline

  • New D.I.C Head

Reputation: 6

  • View blog
  • Posts: 44
  • Joined: 26-Dec 09

Re: reading text file storing information technology into an array

Posted 04 Apr 2010 - 06:28 PM

The reason null is printing out is because the String parameters you pass to printResults are null.

The reason why they are null is because when y'all telephone call getAdjective and getNoun, both those methods are returning a zilch Cord object.

The objects are null because you when you admission the adjectives and nouns arrays, the String objects in the arrays are almost all set up to nada since yous never prepare them properly.

Once you set the readFileIntoArray method(which y'all just demand one, non two versions), this should ready the problem.


#6 one thousand-e-g-a-z User is offline

Reputation: 497

  • View blog
  • Posts: ane,457
  • Joined: 19-Oct 09

Re: reading text file storing it into an assortment

Posted 04 April 2010 - 07:11 PM

@carden2 Accept you got your Scanner and File objects looking like this?

                  File ff = new File("filename.txt");   Scanner ss;   try{ 	ss = new Scanner(f);   }  catch(IOException east){  	Organisation.out.println("File Not Plant");   }                

This mail has been edited by yard-due east-m-a-z: 04 April 2010 - 07:12 PM


#seven carden2 User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: xiv
  • Joined: 25-March 10

Re: reading text file storing it into an array

Posted 04 April 2010 - 07:56 PM

View Postm-e-k-a-z, on 04 April 2010 - 06:11 PM, said:

@carden2 Accept you got your Scanner and File objects looking like this?

                    File ff = new File("filename.txt");   Scanner ss;   try{ 	ss = new Scanner(f);   }  catch(IOException e){  	System.out.println("File Non Found");   }                  

yah i've got that put int their now and information technology does compile. it notwithstanding doesn't run right though i go an fault.

Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(File.java:222)
at InsultGenerator.readFileIntoArray(InsultGenerator.java:32)
at InsultGenerator.main(InsultGenerator.java:20)

thats the error that i become. i tried to email the instructor to get some better advice on how to get my text files to read into an array but never got a effect. i call back if i can just fix my read data like said in post above i could figure this out. I really appreciate all the help i been getting here. do you know whatever tutorials or something that shows how to read the text file into an array with scanner. I tried looking most yesterday earlier coming to this forum for help.


#viii m-e-1000-a-z User is offline

Reputation: 497

  • View blog
  • Posts: i,457
  • Joined: 19-October 09

Re: reading text file storing it into an assortment

Posted 05 Apr 2010 - 09:16 AM

Have a wait at the Tutorials and Snippets section, in that location are some great resources out at that place for learners.

Anyways heres an instance using Arrays.

import java.io.File; import java.io.FileNotFoundException; import coffee.util.*; public class equals {  	//Scanner and File Objects 	static Scanner s;  	static File f;  	public static void main (Cord [] args){  		//Instantiate File with file name inside parameters 		f = new File("examination.txt"); 		//Instantiate Scanner s with f variable within parameters 		//surround with attempt and take hold of to run across whether the file was read or non 		endeavour { 			s = new Scanner(f); 		} catch (FileNotFoundException e) {  			e.printStackTrace(); 		} 		//Instantiate a new Array of Cord type 		String theWord [] = new String[11]; 		//while it has next .. 		while(due south.hasNext()){ 			//Initialize variable  			int i=0; 			//store each word read in array and use variable to move across array 			theWord[i]=south.next(); 			//print  			Organization.out.println(theWord[i]); 			//then we increment so nosotros tin shop in the next array alphabetize 			i++;  		}  	} }                


#nine carden2 User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 14
  • Joined: 25-March x

Re: reading text file storing it into an array

Posted 06 April 2010 - 04:37 PM

i finally got it solved. anyone interested in seeing the finished program only let me know i'll send you the code. thanks for all the assist


#10 m-e-yard-a-z User is offline

Reputation: 497

  • View blog
  • Posts: one,457
  • Joined: nineteen-Oct 09

Re: reading text file storing it into an array

Posted 06 Apr 2010 - 04:twoscore PM

Glad you got your program working :)


  • Java

mcmillanupre1964.blogspot.com

Source: https://www.dreamincode.net/forums/topic/166104-reading-text-file-storing-it-into-an-array/

0 Response to "How to Read a Text File in Java and Store It in an Array"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel