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.
Related
Can someone help me with this java program that I've been puzzled on for a while. I'll post the question alone with the code but its a Files in java that I've recently started and I'm having trouble adding a loop counter variable to hold and display the number of names stored in the file.
For better understanding here the question I'm working on:
Assume that a file containing a series of names (as strings) is named names.dat and exists on the computers disk. Design a program that displays the number of names that are stored in the file. (Hint: Open the file and read every string stored in it. Each time you read a string, increment a counter variable. When you've read all the strings from the file, the counter variable will contain the number of names stored in the file.)
I don't know how much trouble it will be to aid assist being that this question is file related in java.
Here is my java code so far for better understanding:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Item_Counter {
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0;
int sum = 0;
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat");
Scanner bot = new Scanner(namesFile);
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
System.out.println("The file has" + numLines);
}
}
Feel free to replace my file path and name that is a simple notepad document containing a few names, with your own if necessary.
You have some errors in your code, the way Scanner works for file reading is simple, you open the file the way you did like this : Scanner bot = new Scanner(namesFile); but in order to go to the next line you need to do bot.nextLine() so if you do it before you are in the while or do it twice it will go on 2 lines, so you just need to do like this :
public static void main(String[] args) throws FileNotFoundException {
int numLines = 0; // initialise variable
File namesFile = new File("C:\\Users\\Tyrese\\JAVA 2\\Chapter 10\\names.dat"); // fetch the file
Scanner bot = new Scanner(namesFile); // open the file
while (bot.hasNextLine()) { // while the file has a next line -> go on
numLines++; // add +1 to the variable numLines
numLines = bot.nextLine(); // go to the next line (if it has one)
}
System.out.println("The file has" + numLines); // print the result
}
You can ask me if you have any further questions
This is the problematic part of your code:
System.out.println(bot.nextLine());
while (bot.hasNext()) {
numLines = numLines + 1;
numLines = bot.nextInt();
}
Your println types a line being read and therefore that line will be ignored later. You need hasNextLine in the while loop and nextLine instead of nextInt.
Fix:
while (bot.hasNextLine()) {
numLines = numLines + 1;
bot.nextLine();
}
You can compute the sum of integers inside a file similarly. However, the actual solution depends on the structure of the file. If the file contains the integers as lines, without white characters beside the newline, such as
1
5
4
7
2
7
then the solution is:
int sum = 0;
while (bot.hasNextLine()) {
sum += 1;
bot.nextLine();
}
however, if the file is a list of numbers, separated by space, such as
3 7 8 2 8 3 6 9
then you read the content of the file via
String content = bot.nextLine();
String[] splited = str.split("\\s+");
int sum = 0;
for (int index = 0; index < splited.length; index++) {
sum += Integer.parseInt(splited[index])
}
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.
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.
In my class we're using methods to calculate data from a text file. If I had a file that looked exactly like this:
Bob
25
Molly
30
Dylan
10
Mike
65
Is there anyway to pull this data from a file and then send it to a method to calculate, and then return that calculation to display on main? I'm confused as to how Java would be able to skip each line and calculate the numbers instead of the persons name. I was thinking about using inputFile.nextDouble(); and inputFile.nextLine();. But how would I be able to set a String read the lines in the text file if I'm supposed to readthose text file lines variables as doubles? Sorry for all of the questions, I've been stuck on this for a long time and it's driving me crazy >.
You should just alternately use nextLine() and nextInt()
Scanner sc=new Scanner(new File(/* Path to the file*/));
int i=0;
while(sc.hasNext())
{
if(i==0)
{
name=sc.nextLine();
}
else
{
number=sc.nextInt();
}
i=1-i;
}
I recommend you to use an ArrayList to read the full file:
Scanner s = new Scanner(new File(//Here the path of your file));
int number;
String name;
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now you have all the lines of your file (as a String) so now you can operate with the full data that it's inside.
Further, the numbers are in the even lines so you can use a loop to through all the lines and check if the line that you are using now it's even or not.
for(int i = 0; i < list.size(); i++)
{
if(i%2 == 0)
{
number = Integer.parseInt(list.get(i));
//You can use the references to your methods with this number
}
else
{
name = list.get(i);
}
}
With the % you will get the rest of the division (I'm using a property of pairs numbers). With Integer.parseInt you will parse your String to int.
So now you will be able to use this numbers to operate or whatever you want.
EDIT: Here you have an example without using ArrayList. In this case I'm going to use nextLine() and nextInt() functions:
Scanner s = new Scanner(new File(//Here the path of your file));
int count = 0;
int number;
int name;
while(s.hasNext())
{
if(i%2 == 0)
{
number = s.nextInt();
s.nextLine();
//You can use the references to your methods with this number
}
else
{
name = s.nextLine();
}
count = count + 1;
}
If you have doubts about why I'm using s.nextLine() after number without storing any value you can look my answer to this question: Why isn't the scanner input working?
I expect it will be helpful for you!