I have a problem in handling two concurrent Scanner objects.
One scanner is used to determine the number of lines in the file and the other scanner is used to fetch the lines and add it to an array.
The reason is becasue to declare an array we need the size of an array, which is why I'm using the first scanner.
I'm not getting any errors, just a blank console.
File file = new File("E:\\"+fileName);
Scanner inputSize = new Scanner(file);
inputSize.next();
int size = 0;
while(inputSize.hasNext()) {
size = size + 1;
}
inputSize.close();
Scanner inputStream = new Scanner(file);
PermissionSetTabSetting[] record = new PermissionSetTabSetting[size];
PermissionSetTabSetting tabSetting;
int count = 0;
inputStream.next();
System.out.println(inputStream.hasNext());
for(count = 0; inputStream.hasNext() ; count++) {
tabSetting = new PermissionSetTabSetting();
String data = inputStream.next();
String[] permissionSetTabValues = data.split(",");
System.out.println("Line:" + data);
}
If you are reading from a text file, why not use Java 7 Files.readAllLines? It stores all lines into a List<String> and then you can use the list size to instantiate the array, as ryburger said:
List<String> data = Files.readAllLines(new File("E:\\" + filename).toPath());
PermissionSetTabSetting[] record = new PermissionSetTabSetting[data.size()];
If you only need the first scanner to make the array size for the second one, just use a List. Then when you need the size for some other reason, when the list is full you can do listName.size().
Related
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
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]);
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()]);
I have a file that has a different integer on each line. for example:
5
4
3
2
1
I am trying to write a program to run through each int, and put that int into an array. So far, my code is:
Scanner sc = new Scanner(args[0]);
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
intArray = new int[lines];
int counter = 0;
while(sc.hasNextInt()) {
intArray[counter] =sc.nextInt();
counter++;
}
My program creates the array with the right number of indices, but it is never going into the while loop for the scanner. I have no idea why this is, as it looks like I have the same code according to this page.
Unless your file path is space separated numbers, you won't get any numbers. The Scanner was scanning the file path (as a String), not the file.
Scanner sc = new Scanner(new FileInputStream(args[0]));
And FYI, it would be more clear if you used a List rather than reading the file twice.
I was trying to take the input of the filename from the user and then proceed to doing all the calculations. but it keeps returning me an error. the file exists in the same directory.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];
for (int i=0; i<rows;i++){
for (int j=0; j<cols;j++) {
matrix[i][j]= scanner.nextDouble();
}
}
System.out.println(rows);
System.out.println(cols);
for (int i=0; i<rows; i++)
{ for (int j=0;j<cols;j++) {
System.out.println(matrix[i][j]);
}
}
}
}
There is one issue with the code. The scanner will just give you the name of the file as string from command line. So, you need to first get the command line argument and then create one more scanner using the constructor which takes file object. e.g.
Scanner scanner = new Scanner(System.in);
Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
String rowLine = fileScanner.nextLine();
System.out.println(rowLine);
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim())
You realize that you are only using a Scanner of type System.in, right? This means that you aren't even looking at a file, you are looking at user input only. This is regardless of whether you have the first line commented out or not. To use a file, you could use a FileInputStream or a couple other File handling classes.
FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream
Heres the java docs for FileInputStream: http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
Edit: After seeing your comment on what the actual error was, I realize there are more problems with the code than just the way you are handling input. Your error is almost certainly happening at one of the first 2 array accessors, the arr1.trim() calls. That means the user input has nothing on the right side of the "=" sign, or there is no "=" sign in the user input.