looping method for a constructor - java

How should i loop this constructor? Arguments are passed from a text file. I've tried a while-loop, but it does not even read the first line of my text file. My text file contains the ff:
s0,a,s0,a,-1 (--next line--) s0,b,s0,b,-1. If I don't use a loop, it gets the contents of my text file, and passes it to the constructor.
EDIT: i've corrected and marked the constructor to be looped. If I include the second while-loop, it does not get the contents of the text file.
Edit2: the first while loop puts the contents of my text file to an array named argument. The 2nd while-loop does the looping for passing the contents of the argument array to the variables, which then passes it to the constructor. This 2nd while-loop doesn't work.
Scanner scanner = new Scanner(new File("D:\\Kirk\\Documents\\NetBeansProjects\\TuringMachine\\src\\turingmachine\\Algorithms.txt"));
String data = scanner.nextLine();
String[] arguments = data.split(",");
StringTokenizer st = new StringTokenizer(data);
int i = 0;
while (st.hasMoreTokens()) { //loop for putting contents of text file to array
arguments[i++] = st.nextToken();
}//end loop
while(scanner.hasNextLine()){ //loop transition function(not working)
String fromstate = arguments[0];
String read = arguments[1];
String tostate = arguments[2];
String write = arguments[3];
int move = Integer.parseInt(arguments[4]);
trans.add(new Transition(new StateTapeSymbolPair(fromstate, read), new StateTapeSymbolPair(tostate, write),move));
//loop the above constructor
}//end while

you are not looping to get data of eah line.
Here an example :
Scanner scanner = new Scanner(new File("Algorithms.txt"));
while(scanner.hasNext()){
String data = scanner.nextLine(); // your line
String[] arguments = data.split(","); // split the line
// getting data for each data inside the line
String fromstate = arguments[0];
String read = arguments[1];
String tostate = arguments[2];
String write = arguments[3];
int move = Integer.parseInt(arguments[4]);
System.out.println(fromstate+"-"+read+"-"+tostate+"-"+write+"-"+move);
}

Related

How to populate array with text from a file using Scanner and then randomly select the text from the array?

I have a text file that contains a list of films:
Kangaroo Jack
Superman
Shawshank Redemption
Aladdin
What I want to do is pass all of these films into an array and then randomly select a film from the array. However it seems to always select 'Aladdin' and I am not sure what I am doing wrong? How can I randomly select films from the array?
public static void main(String[] args) throws FileNotFoundException {
String[] movieList = {};
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
// Reads the whole file
movieList = line.split("//s");
//splits the string by white space characters meaning we will get the full word(s) per line
}
boolean weArePlaying = true;
while (playing) {
char[] randomWordToGuess = movieList[random.nextInt(movieList.length)].toLowerCase().toCharArray();
int wordLength = randomWordToGuess.length;
char[] playerGuess = new char[wordLength];
boolean wordCompleted = false;
...
}
movieList = Line.Split("//")
This line is always overwriting movielist with the last line in the file: Alladin
Rather write it like the following:
ArrayList<String> movieList = new ArrayList<>();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList.add(line);
}
It's important to note that your original approach would have succeeded if all the movie names were on the same line and had no white spice in between their names like this:
KangarooJack Superman ShawshankRedemption Aladdin
loop also wouldn't have been necessary. So it could have been written like this:
String[] movieList = {};
String line = fileScanner.nextLine();
movieList = line.split("//s");
And if you want to get really wild...
String[] movieList = fileScanner.nextLine().split("//");
movieList = line.split("//s"); is only assigning the last movie to the array, so there is only ever one element in the array. Instead, you need to read each line and assign it to an entry in the array.
Maybe something more like...
String[] movieList = new String[4];
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int index = 0;
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList[index] = line;
index++;
}
This assumes that there are only 4 lines in the file, if there aren't then you will have IndexOutOfBoundsException.
You could guard against this in a number of ways. You could put the number of expected lines as the first line of the file and then create the array based on that or you could exit the while-loop when the array is full or you could use a ArrayList, which is a type of dynamic array

Constructing an object using a given file

I'm trying to use a constructor to create an object from a file, the file should contain (on the first line) an Int in String format which is meant to be the number of rows for the MD Array and then has a space followed by another Int in String format. I'm trying to "grab" these two Strings, parse them into an int and then instantiate the MD Array by using these two ints I've "grabbed." I'm just not quite sure where I'm going wrong, as I've just begun using File I/O in my coding. Here's my code.
public SeatingChart(File file) throws FileNotFoundException, DataFormatException, IOException
{
Scanner scan = new Scanner(file);
int rows = 0;
int columns = 0;
String rowStr = "";
String colStr = "";
if (scan.hasNext())
{
rowStr = scan.next();
colStr = scan.next();
}
rows = Integer.parseInt(rowStr);
columns = Integer.parseInt(colStr);
seats = new Student[rows][columns];
scan.close();
}
Any help would be much appreciated :)
From your question, You want to grab two numbers, in string format, separated by a space.
I would grab the entire line then trim the string which ensures there is no space before or after the numbers I need. Then split them based on space.
Look at this simplified step by step example. This example will create a file called numbers.txt then put in it string "5 2". Then the file will be read and taken apart to get the numbers.
import java.util.*;
import java.io.*;
import java.nio.*;
PrintWriter fileWriter = new PrintWriter("numbers.txt", "UTF-8");
fileWriter.println("5 2");
fileWriter.close();
File file = new File("numbers.txt");
Scanner input = new Scanner(file);
String numbersString;
if (input.hasNextLine()) numbersString = input.nextLine();
// Trim the string to ensure you have what you need.
numbersString = numbersString.trim();
// Split both numbers according to the space within them.
String[] numsArray = numbersString.split("\\s+");
// Get your numbers.
int row = Integer.valueOf(numsArray[0]);
int col = Integer.valueOf(numsArray[1]);

Reading from a file rather than from the console

I am getting exception thrown and i think it has to with the ArrayIndexOutOfBounds at the sub string and also do you think the below method would work for getting data passed to my array after parsing
I want this to be read from a txt file like this, on each line:
1
0
1
0
0
1
0
ONE INTEGER PER LINE!!
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
data1 = scanner.nextLine();
}
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}
This is previous working version but it reads from the console. where it would be : 1010101001
System.out.println("Enter the binary bits");
data1 = in.next();
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}
You're reading all the lines and only keeping the last in your data1 variable. That's probably your problem.
You should, instead, handle each value right away while reading the file, and build an ArrayList instead of an array (because you won't know its size beforehand):
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
ArrayList<Byte> covertDataList= new ArrayList<>();
while(scanner.hasNextLine()){
String line = scanner.nextLine(); // the line should be just a number
covertDataList.add(Byte.parseByte(line)); // no substring needed
}
If you want to fail nicely when the file format is wrong, you may surround parseByte with a try/catch block.
About the ArrayList
If you want to use your list as an array, you can just:
use covertDataList.get(i) instead of covertDataArray[i]
use covertDataList.set(i, value); instead of covertDataArray[i] = value;
If you really need an array (I don't see the point here), you can do this:
Byte[] covertDataArray = covertDataList.toArray(new Byte[list.size()]);

Read text file and split each newline into a string array

So basically I'm reading a text file that has a bunch of lines. I need to extract certain lines from the text file and add those specific lines into string array. I've been trying to split each newLine with: "\n" , "\r". This did not work. I keep getting this error as well:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at A19010.main(A19010.java:47)
Here is the code:
Path objPath = Paths.get("dirsize.txt");
if (Files.exists(objPath)){
File objFile = objPath.toFile();
try(BufferedReader in = new BufferedReader(
new FileReader(objFile))){
String line = in.readLine();
while(line != null){
String[] linesFile = line.split("\n");
String line0 = linesFile[0];
String line1 = linesFile[1];
String line2 = linesFile[2];
System.out.println(line0 + "" + line1);
line = in.readLine();
}
}
catch(IOException e){
System.out.println(e);
}
}
else
{
System.out.println(
objPath.toAbsolutePath() + " doesn't exist");
}
String[] linesFile = new String[] {line}; // this array is initialized with a single element
String line0 = linesFile[0]; // fine
String line1 = linesFile[1]; // not fine, the array has size 1, so no element at second index
String line2 = linesFile[2];
You're creating a String[] linesFile with one element, line, but then trying to access elements at index 1 and 2. This will give you an ArrayIndexOutOfBoundsException
You're not actually splitting anything here. in.readLine();, as the method says, reads a full line from the file.
Edit: You can add lines (Strings) dynamically to a list instead of an array, since you don't know the size.
List<String> lines = new LinkedList<String>(); // create a new list
String line = in.readLine(); // read a line at a time
while(line != null){ // loop till you have no more lines
lines.add(line) // add the line to your list
line = in.readLine(); // try to read another line
}
readLine() method reads a entire line from the input but removes the newLine characters from it. When you split the line on \n character, you will not find one in the String. Hence, you get the exception.
Please, refer the answer in this link for more clarity.
You are initializing your String array with 1 element, namely line. linesFile[0] is therefore line and the rest of your array is out of bounds.
Try this:
String[] linesFile = line.split("SPLIT-CHAR-HERE");
if(linesFile.length >= 3)
{
String line0 = linesFile[0];
String line1 = linesFile[1];
String line2 = linesFile[2];
// further logic here
}else
{
//handle invalid lines here
}
You are using array to store the strings. Instead use ArrayList from Java as ArrayList are dynamically growing. after your reading operation completes convert it into array.
String line = in.readLine();
ArrayList<String> str_list = new ArrayList<String>();
String[] strArr = new String[str_list.size()];
while(line != null){
str_list.add(line);
line = in.readLine();
}
// at the end of the operation convert Arraylist to array
return str_list.toArray(strArr);
The issue here is that you are creating a new String array every time your parser reads in a new line. You then populate only the very first element in that String array with the line that is being read in with:
String[] linesFile = new String[] {line};
Since you create a new String[] with one element every single time your while loop runs from the top, you lose the values it stored from the previous iteration.
The solution is to use new String[]; right before you enter the while loop. If you don't know how to use ArrayList, then I suggest a while loop like this:
int numberOfLine = 0;
while (in.readLine() != null)
{
numberOfLine++;
}
String linesFile = new String[numberOfLine];
This will let you avoid using a dynamically resized ArrayList because you know how many lines your file contains from the above while loop. Then you would keep an additional counter (or resuse numberOfLine since we have no use for it anymore) so that you can populate this array:
numberOfLine = 0;
in = new BufferedReader(new FileReader(objFile)); // reset the buffer
while ((String line = in.readLine()) != null)
{
linesFile[numberOfLine] = line;
numberOfLine++;
}
At this point linesFile should be correctly populated with the lines in your file, such that linesFile[i] can be used to access the i'th line in the file.

going to method, pulling info from file, and then returning it after it gets split. I am getting errors

String[] quarters = new String[100] ;
quarters[] = information(fileCheck) ;
public static string information(String a)
{
Scanner inFile = new Scanner (new File(a)) ; // opens connection with file
while (inFile.hasNext()) // loops while more lines in file
{
String line = inFile.nextLine() ; // brings in next line to be broken up
String[] tokens = line.split(", ") ; //stores lines into array tokens
}
inFile.close() ; // close connection to file
return tokens[] ;
} // end information
This is not Java:
return tokens[] ;
Perhaps you mean to return the token array:
return tokens;
If so, declare the method to return String[] not String.
Also, you're not showing us where these lines are located:
String[] quarters = new String[100] ;
quarters[] = information(fileCheck) ;
For all we know they are sitting out naked in the class and not in any method or constructor. If so, that is not Kosher Java since the second line is not a declaration and needs to be in a method or constructor.

Categories

Resources