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()]);
Related
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().
I have a method that's reading a local CSV file and storing it in an array. I keep getting a ArrayIndexOutOfBoundsException when I try to print one of the index of the array.
The method:
public void getCsv() throws FileNotFoundException{
String fileName = "ADCSV.csv";
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
//array of strings
String[] values = data.split(",");
System.out.println(values[4]);
}
inputStream.close();
}
All of the information in the csv is stored as general text. When I try to print this is the output:
"adminCount"
"1"
"0"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at csvTest.test.getCsv(test.java:36)
at csvTest.test.main(test.java:19)
It starts to read the values from that particular column fine. It then errors out.
I feel like I've been looking at the problem for awhile now and looking right past the issue.
Thanks
Change your method to:
public void getCsv() throws FileNotFoundException {
String fileName = "ADCSV.csv";
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data = inputStream.next();
// array of strings
String[] values = data.split(",");
if (values.length < 5) {
System.err.println("not enough values: ");
for (int i = 0; i < values.length; i++) {
System.err.println("value " + i + ": " + values[i]);
}
continue;
}
System.out.println(values[4]);
}
inputStream.close();
}
That should show the problem. I mean it will print out the values of the line where the error will occur. Since we don't know what exactly produced the error this will be a start. Maybe somewhere is a comma where it shouldn't be or it is missing.
If the content of the local CSV file can contain errors then it would be appropriate to check the length of the splitted line and set up an error handling.
I am currently writing my Bachelor's thesis in graph theory and use the java scanner to convert a txt file with edges into my Java class graph. My txt file looks like this:
1 2 72 3
2 3 15 98
4 7 66 49
5 6 39 48
6 9 87 97
8 13 31 5
The ints are ordered as: source vertex, sink vertex, cost, capacity.
My Code looks like:
Graph graph = new Graph(false);
File f = new File("Filepath");
Scanner in = new Scanner(f);
while (in.hasNextLine())
{
for (int i =1; i<= numberEdges; i++)
{
String s = in.nextLine();
try (Scanner inscan = new Scanner(s)) {
while (inscan.hasNext())
{
int source = inscan.nextInt();
int sink = inscan.nextInt();
double cost =inscan.nextDouble();
double capacity = inscan.nextDouble();
Vertex Source = new Vertex(source);
Vertex Sink = new Vertex(sink);
Edge edge = new Edge(Source,Sink, cost, capacity);
graph.addEdge(edge);
}
}
}
}
in.close();
I tried to scan each line in a String and then scan the String into my Variables.
It always throws a "NoLineFound" Exception in the first line of the for loop and if I try it with outputing the lines I get none. But when I disable the second scanner and try again I get all lines in the ouput but at the end still a "NoLineFound" Exception.
I checked my txt File and the last line doesn't have a UTF8 line ending, but I don't know how to give it one.
I think that your problem comes from that :
while (in.hasNextLine()){
for (int i =1; i<= numberEdges; i++)
{
First, iteration is redundant (while or for are unitary enough for reading each line. You have to do choice between them).
Besides if your file has less line than numberEdges, a java.util.NoSuchElementException will be raised.
If the number of line is constant in the file, use a for:
for (int i =1; i<= numberEdges; i++)
remove the enclosing while (in.hasNextLine()). It is not required. Iteration control is already done by the for.
If the number of lines in the file may vary, use only a while :
while (in.hasNextLine()){
But anyway, don't use both.
With Java 8 streams:
Files
.lines(f.toPath())
.map(l ->Arrays.stream(l.split(" ")).mapToDouble(Double::parseDouble).toArray())
.map(a->new Edge(new Vertex((int)a[0]), new Vertex((int)a[1]), a[2], a[3]))
.forEach(graph::addEdge);
You are reading nextLine() in a loop after a single check for hasNextLine(). You need to perform a check after each read in order to avoid the "NoLineFound" exception.
It looks like the nested loop is completely unnecessary. You can read file line-by-line, ignoring empty lines, and build your graph without prior knowledge of the number of edges that it has:
Graph graph = new Graph(false);
File f = new File("Filepath");
Scanner in = new Scanner(f);
while (in.hasNextLine()) {
String s = in.nextLine();
try (Scanner inscan = new Scanner(s)) {
if (!inscan.hasNext()) {
continue; // Ignore empty lines
}
int source = inscan.nextInt();
int sink = inscan.nextInt();
double cost =inscan.nextDouble();
double capacity = inscan.nextDouble();
Vertex Source = new Vertex(source);
Vertex Sink = new Vertex(sink);
Edge edge = new Edge(Source,Sink, cost, capacity);
graph.addEdge(edge);
}
}
in.close();
Just perform a check after reading to avoid the "NoLineFound" exception.
You can use the below code to scan the file:
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
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.