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)
Related
I need to pull integers from a text file and sum them up. I came up with this but I keep getting an error. What am I missing? I need to use a scanner class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class txtClass {
public static void main(String[] args) throws FileNotFoundException {
File txtFile = new File(//text file path//);
Scanner scan = new Scanner(txtFile);
int length = 0;
while(scan.hasNextLine()) {
scan.nextLine();
length++;
}
int array[] = new int [length];
array[length++] = scan.nextInt();
System.out.println(array.toString());
int h = 0;
for (int i = 0; i<array.length; i++)
{
h +=array[i];
}
scan.close();
System.out.print(h);
}
}
As suggested, a lot of the code is not really needed. But presumably the 'error' you get is array index out of bounds. Here:
int array[] = new int [length];
array[length++] = scan.nextInt();
So you allocate an array and immediately access off the end of the array. Let's assume length is 42. Therefore, the allocated array elements have indexes 0 to 41. You try and assign something to array[42]. I'm not sure what you're trying to do with that line.
The alternative guess (which we would not need to guess had you mentioned the actual error message) is that your counting lines leaves the scanner positioned at end of file. so the scan.nextInt() call in the assignment gets you an I/O error.
In any case, the core of the solution is something like
int sum = 0;
while (scan.hasNextInt())
sum += scan.nextInt();
No array is needed.
You wrote in your question
I keep getting an error
That would be NoSuchElementException which is thrown by this line of your code:
array[length++] = scan.nextInt();
This is because you have already scanned the entire file and therefore there is no next int.
Remember that in order for people to help you with errors thrown by your code, you need to post the actual exception and the stack trace as well as your code.
You don't need to save all the numbers in the file in an array in order to get the sum of all the numbers. However if you also want to save all the numbers but you don't know in advance how many there are, you can use a List.
Here is a minimal example of how to read the file – which I assume contains only numbers separated by whitespace – and calculate the total. Of-course you need to replace text file path with the actual path to the text file.
File txtFile = new File("text file path");
try (Scanner scan = new Scanner(txtFile)) {
int total = 0;
while (scan.hasNextInt()) {
total += scan.nextInt();
}
System.out.println("Total: " + total);
}
catch (FileNotFoundException xFileNotFound) {
xFileNotFound.printStackTrace();
}
Note that the above code uses try-with-resources.
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.
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.
I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.
The code I have writen is as follows
public static void main(String[] args) throws IOException{
Scanner Input = new Scanner(new File("newestcode.txt"));
Integer[] digits = new Integer[100];
int h = 0;
while(true){
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}
}
in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day
try {
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}catch (NoSuchElementException e){
break;
}
First of all, if you're not sure about amount of ints in your file, don't try to store them into fixed-size array. Use ArrayList instead.
Also don't use endless loop while(true) but consider using Input.hasNext() to check if there still is something to read from file.
And one more. You're trying to print value after increment. This means that you're adding element on 0 position but trying to read it from 1 position. Make increment on the end of the loop.
Scanner Input = new Scanner(new File("newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while(Input.hasNetxt()){
digits.add(h, Input.nextInt());
System.out.println(digits.get(h));
h++;
}
You should use the input.hasNext() method to check whether the input has any more 'int' before using it.
In order to support any length of int elements, you cannot set the array to a fixed length of 100, you need to use an ArrayList to add elements dynamically.
Scanner input = new Scanner(new File("./newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while (input.hasNext()) {
digits.add(h, input.nextInt());
System.out.println(digits.get(h));
h++;
}
Note: You need to print digits[h] before increasing the h.
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.
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);
}
}