How to avoid a "java.util.NoSuchElementException" crashing my program - java

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.

Related

How to sum up all ints in a text file?

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.

How to read both integers and doubles from txt fle

i have a text file and i want to read the integers and doubles. I dont know how many values i have to read. The first value in the line is always the integer and the second is always the double. I want to save the value of the first line seperately.
200
11010 0.004
500 0.02
637 0.018
How to create 2 arrays and save the values, so i can use them later? I am not allowed to create a new class. I tried to use Point but cant store doubles.
Scanner scanner = new Scanner(new File(args[0]));
int cores= scanner.nextInt();
System.out.print(cores);
while (scanner.hasNext()) {
int x = scanner.nextInt();
double y = scanner.nextDouble();
System.out.printf("x");}
I' ve tried the code above but throws out Exception
You can use simple file handling approach to read the file line by line, For the first line you can use a flag to mark the line and sent the file to remote location you want to save the data. Then for all later lines you can split the string on the basis of " " (space). Post which once you have stripped the elements of the resulting array you can typecast and append the element at first index to integer array. And the second element (typecast before append) to the double array. This shall work absolutely fine with any length of file.
A demo code for the same is as following:
public class ReadLineByLine
{
public static void main(String args[])
{
try
{
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis);
String tempLineData = "";
int flag = 0;
String[] elements;
List<Integer> ints = new ArrayList<Integer>(
List<Float> floats = new ArrayList<Float>(
while(sc.hasNextLine())
{
if(flag == 0){
// Place the operation with the first line here
flag++;
}
tempLineData=sc.nextLine();
elements = tempLineData.split(" ");
ints.add((int)elements[0].trim());
floats.add((float)elements[1].trim());
}
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

Java: int array returning as 0s

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)

Reading from a text file and changing the strings to int's to be entered in arrays is not working

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.

Read multiple lines from console and store it in array list in Java?

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);
}
}

Categories

Resources