I am having a problem with the Scanner class method hasNextLine() (or the hasNext() method). Basically, I am trying to read from a text file that has a list of integer values. I need to read through the text file and store the values that are there in an array (not an arrayList). The code below first goes through the text file to "see" how many values are there. I'm doing this because I can't think of another way to count the total number of integers that are in the text file, and I need to know how long my array has to be.
That being said, once I do that it seems that the hasNextLine() method (or the hasNext() method) "stays" at the bottom of the text file once I loop through:
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException
{
int y = 0; //stores numbers from the text file below
int counter = 0; //stores the number of datapoints in the text file to read from
File f = new File("Test Data.txt");// load an external file into a variable of type File.
Scanner reader = new Scanner(f);//instead of using System.in use f.
while (reader.hasNext()) // this will read the file's contents line-by-line
{
y = reader.nextInt();
counter++;/*stores the total number of integers in the Test Data.txt file so I can
know how long my array that stores the numbers from the txt file needs
to be.*/
}//ends loop
System.out.println("YOU HAVE " + counter + " DATA POINTS IN THE FILE");
int [] myNumbers = new int[counter]; //will store the integers from a data file
for (int i = 0; i < counter; i++){
if (reader.hasNext()){
System.out.println(i);
myNumbers[i] = reader.nextInt();
}//ends if statement
}//ends loop filling array
reader.close();
}
}
Is there a way to send the scanner "back to the top" of the text file WITHOUT creating a new scanner object? I know I could just create a new Scanner object, and then just loop and store each data point in an array, but it seems like there should be another way to do what I need to do. Is there? The documentation for the method in question doesn't mention much detail. I tried using the reset() method but that did not work.
I am not using an ArrayList because of a condition of the project I am working on. I understand that I could use an arrayList and not have to worry about counting the number of data values in the text file. However, the student I am helping has not learned about arrayLists yet as his class does not include them in the beginner course he's taking.
When reading the file for the second pass, just dispose the old scanner and get a new one. It is all in one line:
reader = new Scanner(f);
This will overwrite the reader with a reference to a new Scanner, one that reads from the beginning of the file. The old Scanner instance, which is no longer accessible will automatically be cleared by the garbage collector.
Related
I'm trying to pull an array from a text file (see radiation[] below), but it keeps returning zeroes. I'm happy to provide the .txt. file.
The text file I'm using has a range of integers from 1-200 (the first is 16), but the code appears to be reading the file as all zeroes. Any ideas about what's going on with this? Thanks for the insights!
public static void main (String[] args) {
int radCtr = 0;
Scanner scanner = new Scanner(new File("C:/Users/u23s57/Documents/4_22_18_radiation.txt"));
while (scanner.hasNextLine()) {
radCtr++;
scanner.nextLine();
}
int [] radiation = new int [radCtr];
int i = 0;
while(scanner.hasNextInt()){
radiation[i++] = scanner.nextInt();
}
for (int y = 0; y < radiation.length; y++) {
System.out.println(radiation[y]);
}
int max = getMax(radiation);
System.out.println("Maximum Value is: "+max);
}
while (scanner.hasNextLine()) {
radCtr++;
scanner.nextLine();
}
This loop consumes all the lines in the file. So when you get to here:
while(scanner.hasNextInt()){
There are no more ints to read.
You either have to:
Re-open the scanner after the first loop.
Allocate an array of arbitrary size (that is at least as large as it needs to be)
Use a data structure that you don't need to know the size of in advance (e.g. a List).
Do it without storing all the data. You don't need to store it all to get the maximum.
Because of "scanner.hasNextLine()" you don't have any integers left anymore.
Therefore, you should use different scanners.
Just another thing, it might be better to not use the scanner but bufferedreader. In my opinion especially when you're going to use delimiter (which i don't see yet though)
Basically I am asking for the filename with a method called CS160Input (provided by my instructor) to ask for the filename. The text document has a bunch of entries each on their own lines, and I am trying to assign each number to a place in an array, but I am failing to actually write to the array. I know it is finding the file, because when i print out the counter, it tells me the correct amount of lines in the file. But when I try to print out a place in the array, I tried index 3 as you can see in my code, and it gives me 0 regardless of what I try. I tried creating an array of strings first and I ended up getting null for each index value as well.
public static void caclulate() throws FileNotFoundException {
String fileName = CS160Input.readString("Please enter the name of the file: ");
Scanner sc = new Scanner (new File (fileName));
int value, counter = 0;
int array[] = null;
while (sc.hasNextLine()) {
sc.nextLine();
counter++;
}
Scanner scanner = new Scanner(new File(fileName));
int[] calcArray = new int [counter];
int i = 0;
while(scanner.hasNextInt()){
calcArray[i++] = scanner.nextInt();
}
System.out.println(calcArray[3]);
System.out.println(counter);
}
Thanks to #Gendarme pointing out that hasNextInt() could be spitting out false if there were values in between, it made me take a closer look and I realized that in a previous program the numbers being written to the text file were doubles with 2 decimal places. Once I changed to hasNextDouble(), the program worked as intended.
I am trying to read a file, which the user inputs, and the file has numbers and characters. I only want to store the numbers in an Arraylist but I keep getting stuck, help would be greatly appreciated. This is what I have. Sorry if this has been answered, I am new to the site.
import java.util.*;
import java.io.*;
public class ArrayListClient {
public static final int SIZE = 100;
public static void main(String[] args) throws FileNotFoundException {
String fileName, fileName2;
UnorderedArrayList list1 = new UnorderedArrayList(SIZE);
Scanner input = new Scanner(System.in);
System.out.print("Please input the name of the file to be opened for the first list: ");
fileName = input.nextLine();
System.out.println();
Scanner inputFile = new Scanner(new File(fileName));
int num = inputFile.nextInt();
while(inputFile.hasNextInt()) {
int num2 = inputFile.nextInt();
list1.insertEnd(num);
num = num2;
}
list1.print();
}
}
the input file is 13 c v b 25 34 x x 67 56 10 a a 20 27 2 a s 5 1 45 59
The loop you provided is correct, although you don't need this line outside of the while loop:
int num = inputFile.nextInt();
If the file you provided didn't have a Integer then this would crash your program.
I think you can simply write this and it should work:
while (inputFile.hasNextInt()) {
int num = inputFile.nextInt();
list1.insertEnd(num);
}
The loop checks to see if there is another Integer left in the file (inputFile.hasNextInt()) and then gets it to add to the list (inputFile.nextInt()).
This sounds like it could be a homework question, so I'm hesitant to just give the answer, but if I were you, I would consider writing a filter function (make it a lazy filter if you have to consider files that are very large/won't fit in memory). Your filter function can try Integer.parseInt(yourString); and catch any NumberFormatExceptions that occur because it tried to parse a letter. This approach has the obvious danger of using exceptions to control program flow (normally considered bad practice), but you won't have to traverse the list twice.
Your other obvious option is to write a filter that filters the characters out so that you are only left with number strings, and then just run parseInt over those number strings to turn them into integer values. If performance is a concern, you can avoid double-traversing the list by writing functions that validate a single string value (reject if it's not a number), and then parse it into an int if it is a number, and then add the parsed integers into your array as you go within a foreach loop.
You are most of the way there already since integer detection is built into the Scanner class and the Integer class contains the parseInt() method. Just mutate an array which you define outside of a for each loop and you're good to go.
I need to know how to do computations on a user inputed list of numbers. Here's my code so far, I'm lost as to how to proceed. I need to write a code that asks whether or not the user wants to manually input numbers or upload from a file. If user chooses manual, I have to find the average, min, max, and stand. dev. of the numbers they input. Any help would be appreciated
import java.io.*;
public class computation {
//main method starts
public static void main (String[] args) throws Exception {
//create text input reader
InputStreamReader get = new InputStreamReader(System.in);
BufferedReader got = new BufferedReader(get);
//create a text printer
PrintWriter send = new PrintWriter(System.out,true);
//defining a string type variable for user input
String answer1;
//asks the user if they want to input data from keyboard
String question = "Do you want to input data manually? Enter y or n";
send.println(question);
//system reads user input
answer1 = got.readLine();
if (answer1.equals("y")) {
send.println("Enter numbers separated by spaces");
String datacurrent = got.readLine();
} //end of "y" if
if (answer1.equals("n")) {
send.println("Enter the path of your data file");
} //end of "n" if
} //end of main method
} //end of class computation
I just ran your program, it seems alright.
(A) What to do when values inputted through console ?
Split the string into an array, extract each number and then calculate Average, Min, Max, and Stand deviation.
For ex:
String[] numbers = datacurrent.split(",");
for(int i=0; i<number.length; i++)
{
....
}
(B) What to do when inputted as file path ?
You will have to read the file using File Stream/Buffer Reader.
BufferedReader reader = new BufferedReader(new FileReader(Your string variable pointing to path));
And then loop through file data.
Note: You need to know the text file format in order to loop through the file content.
You might want to look at the newer class System.console that we got that faciliates easier console i/o. Your program shows attempt and if you study one or two good Java books you will beable to write this program error-free. Two good new Java books are the Sierra / Bates OCJP study guide and the new A Press Java 7 book. I recommend you take a read or two from one or two of these books and you will learn how to use ? System.console for console i/o.
System.out.print("Enter something:");
String input = System.console().readLine();
Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}