Scanner issue with "hasNextInt()" - java

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.

Related

Read only one line of Integers from a file

I am trying to read a file which contains integers. The file has 40 lines, each having 80 integers. However when I run the following code, I get 40 lines and 3200 integers in each line (it reads the entire file for each line). How can I fix this.
while(input.hasNextLine()){
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt()){
++columns;
colReader.nextInt();
}
colReader.close();
}
You can also simplify your code somewhat. You can keep on reading integers one by one.
Scanner input = new Scanner(new File("f:/numbs.txt"));
while (input.hasNextInt()) {
int v = input.nextInt();
System.out.println(v);
}
Because you are duplicated the loop, if you want to read a file, you can do the next
BufferedReader bufferReader = new BufferedReader(new FileReader(new File("")));
int line;
StringBuilder stringBuilder = new StringBuilder();
while ( (line =bufferReader.read()) != 0 ) {
// Do something
}

Read Strings separated by newline using BufferedReader into a String array

I've read number of such questions but they are all about reading inputs from a txt file. I want to read input from user and not from the file.
I've input like following:
6 //number of total Strings to store in array
babu
anand
rani
aarti
nandu
rani
I've tried the following code to take such input in a String array:
int n = in.nextInt(); // n= 6 here
String[] s = new String[n]; //String array of size 6 here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
s = br.readLine().split("\\s");
}
catch(Exception e){
System.out.println(e);
}
Is the regex provided to the split() is correct or not? What I'm missing here? If this is not correct approach than what should I do for this problem?
Regex are using backslashes (\) while you used slashes //s, correct one is \\s.
But this split is not needed, you just need the readLine, and you will get what you need (assuming you don't want to split words in the line).
You should use a loop to read all the data (and get rid of Scanner, that you appear to have in the in variable):
String[] s = null
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) {
int n = Integer.parseInt(br.readLine());
for (int line = 0; line < n; line++) {
s[line] = br.readLine();
}
} catch(Exception e){
System.out.println(e);
}
Move the third line before the first one.
Then use this in your new second line:
int n = Integer.parseInt(br.readLine());
And, of course, you need a loop to put your input strings into an array.
This should help.

How to properly read integer from file in Java

I have read previous posts and tryed to integrate code in to my project.
I am trying to read integers from my txt file.
I am using this method:
static Object[] readFile(String fileName) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}
I don't know the size of data, so i am using List
in main calling method:
Object [] arr = readFile("C:\\02.txt");
System.out.println(arr.length);
I am getting that the array size is 0;
The integers i am trying to read from the file is binary Sequence. (1010101010...)
I thought that the problem is connected with scanner maybe he thinks that it is not the integer.
You can use BufferReader instead :
String line = "";
List<Integer> tall = new ArrayList<Integer>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine())!= null) {
tall.add(Integer.parseInt(line, 2));
}
br.close();
}catch(IOException e) {}
If you are reading data in binary form then consider using nextInt or hasNextInt with radix.
while (scanner.hasNextInt(2)) {
tall.add(scanner.nextInt(2));
}
Otherwise you will be reading integers as decimals so values may be out of integers range like in case of
11111111111111111111111111111111

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()]);

file input from the user

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.

Categories

Resources