Issue with parallel arrays and reading integers / doubles from file - java

I have an issue with parallel arrays and getting the program to read integers and doubles. For example, I have a text file with these values:
1234 99.58
5678 1854.99
The first number being an account number and the second number being the balance of the account. I'm not sure how to get them into a parallel array (int[] accountnumber, double[] balance) while going down the list of ideally 10+ accounts and balances.
I've tried filling the arrays separately without success, which doesn't feel like the most efficient method possible. I've tried breaking down the "(int = 0; i < maxAccts; i++)" so I could use the "i" variable for both without resetting it.
public static int readAccts(int[] acctNum, double[] balance, int maxAccts, File myinput, Scanner inputFile) throws IOException {
maxAccts = 0;
while(inputFile.hasNextInt()) {
//Test for reading integers accurately
//System.out.println(inputFile.nextInt());
maxAccts++;
inputFile.nextLine();}
//Test for maxAccts
System.out.println(maxAccts);
acctNum = new int[maxAccts];
balance = new double[maxAccts];
Scanner AccountFiller = new Scanner(myinput);
while(inputFile.hasNext());{
int i = 0;
while (i < maxAccts) {
acctNum[i] = AccountFiller.nextInt();
balance[i] = inputFile.nextDouble();
i++;}
//for (int i = 0; i < maxAccts; i++)
System.out.println(acctNum[1]);}
return maxAccts;
}
I keep getting this error below:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
At this point, I don't know why it's going wrong. In my head the cursor in the document should be right after the integer (account number), and I'm not getting an issue with that part.

You might want to fix your while loop
Your second while loop looks like this:
while(inputFile.hasNext());{
Which has a semicolon between the while and the curly brace, which means that the body of the loop is empty and after it is done looping, you run the code inside the curly braces.
The loop should be like this:
while(inputFile.hasNext()) {
This causes the error of reading the nextDouble since we just consumed the scanner's source until there is no next.
You might also want to check again how you want to read the file, since the first part doesnt really make much sense to me, it appears you just skip over all ints found in the file (while counting how many times you skip)

Related

Calculating factorial for 0 leading to NoSuchElementException

I got to calculate the factorial of a number. As a fact factorial of 0 is 1. So I included that case in the function as well.
here's the code:
import java.util.*;
public class Factorial {
static int fact(int n) {
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
public static void main(String args[]) {
int i, fact = 1;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
}
but if I'm giving input as 0, some exception was raised
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Factorial.main(Factorial.java:14)
How to resolve this situation?
Edits:
I have changed the exception.All apologies for the thing that yes the code wasn't even 26 lines. I had put some code above as comments before posting just the code here.
This ain't a duplicate. As of the fact I want to know why it doesn't accept 0 as an input. It works perfect for all other inputs.
I use an online Compiler https://www.tutorialspoint.com/compile_java_online.php
Works fine with Java Compiler of the PC JDK 1.7 ,but raises exception on online IDE.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available. Link.
Modified your code and added hasNextInt so that NoSuchElementException is not thrown and sc.close() to close the resource at the end of main method
public static void main(String args[]) {
int fact = 1;
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
sc.close();
}
The online IDE is probably doing some kind of pre-processing of the data that
don't plays very nice with zeros.
TutorialPoint has online compilers for multiple languages and is very likely
that these all share some common backend that does the magic of passing text
from your browser to their servers. I'm not sure what kind of processing is
happening behind but I can imagine that is something like trimming the
unnecessary zeros from the left of the numbers or something like that.
I have encountered the opposite problem in standard C with the function sscanf,
which expected to fail (return 0) when the input string is empty just like its
sister function scanf but it still returns sucess and stores zero in the integer
variables.
By the way, if you just add a leading space or \n to the zero, everything works
just fine.

Out of Bounds Exception, need advice

I've read gone through the tutorials, so by all means, if you see something that I've done wrong here, please tell me so I can learn to better-participate on this site.
The getPerishedPassengers method below is giving me an out of bounds exception. I have researched and researched, and I seem to be populating the array properly, and I don't know what is wrong with the method that I've created either. Could someone guide me in the right direction as to how to overcome this exception? Thank you folks!
Here's the main/method:
int passengerMax = 2000;
int passengerActual = 0;
//Create a 2D array that will store the data from the .txt file
String[][] passengerData = new String[passengerMax][6];
//Constructor to read the file and store the data in the array
Titanic(String file) throws FileNotFoundException {
try (Scanner fileIn = new Scanner(new File(file))) {
//Conditional for reading the data
while (fileIn.hasNextLine()) {
//tab through the data to read
passengerData[passengerActual++] = fileIn.nextLine().split("\t");
}
}
}
public int getTotalPassengers() {
return passengerActual;
}
//Method for getting/returning the number of passengers that perished
public int getPerishedPassengers() {
int count = 0;
//For loop w/conditional to determine which passengers perished
for (int i = 0; i < getTotalPassengers(); i++) {
int survive = Integer.parseInt(passengerData[i][1]);
/*The program reads the file and if 1, the passenger survived. If 0,
the passenger perished. Conditional will add to the count if they
survived*/
if (survive == 0) {
count++;
}
}
return count;
}
Here's the stacktrace I'm receiving. I can include the test code as well if you folks would like. Thanks in advance:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at titanic.Titanic.getPerishedPassengers(Titanic.java:66)
at titanic.testTitanic.main(testTitanic.java:68)
Java Result: 1
From what I can see above, the issue is in the line:
int survive = Integer.parseInt(passengerData[i][1]);
My best guess, lacking your input file, is that when you are reading the file, at least one line creates an array of length 0 or 1. In all likelihood, if the last line of the file is an empty line, it would be this line which is causing your array out of bounds exception, as the split would create an array of length 0. Another cause would be a line which lacks any tab in it at all (say a space instead of tabs, etc.) will create a length 1 array, of which passengerData[i][1] will not exist, only passengerData[i][0] will.
Assuming that your input file does not have any lines which are improperly formatted / lack the appropriate number of tabs, I would suggest changing this line in the file read loop:
passengerData[passengerActual++] = fileIn.nextLine().split("\t");
to:
String incomingLine = fileIn.nextLine().trim();
if (null != incomingLine && !incomingLine.isEmpty()) {
passengerData[passengerActual++] = incomingLine.split("\t");
}

reading string and integers from a text file in java

/*This assignment is to create 2 parallel arrays – jobs& salaries
*Read file from “careers.txt” into arrays
*one line – job
*next line –salary
*Sort Salaries {from highest}
*then swap jobs if salary swapped
*Display output of careers and salaries from the highest on a formatted table.
*
*/
package assignment7;
import java.util.*;//importing Scanner
public class Coordinator
{
public static void main(String[] args) throws Exception
{// the main method creates the arrays and calls on each method to perform
//its work.
String [] job = new String[20];//creating a string array having 20 spaces
int[] salary = new int[20];//creating an integer array having 20 spaces
int count;// number of spaces actually occupied in the array
**count = readFile(job, salary);**// calling a method to read text into both
//arrays and return the number of spaces
//occupied in the array
sorter(job,salary,count);// calling on method to arrange file from highest
//to lowest
display(job, salary,count);// calling on method present the output
}
public static int readFile(String[] jobber, int[] salaro) throws Exception
{ // this method reads a text file and copies into arrays and also
//returns the number of spaces occupied in the array
int n = 0; //keeps track of number of times a line is fed into an
//array
//set up a file class object linked up to the name of the file to
//be read
java.io.File unread = new java.io.File("career.txt");
// create a scanner instance to read the input from the file
Scanner infile = new Scanner(unread);
/*This while loop reads line of text into the arrays, it uses
* boolean
* function hasNextLine() and the created scanner instance.
*/
while (infile.hasNextLine() || infile.hasNextInt())
{
jobber[n] = infile.nextLine();
**salaro[n] = infile.nextInt()**;
n++;
}//end while
infile.close();//close scanner class
return n;// return number of spaces filled
}//end of readFile method
public static void sorter(String[] jobestic, int[] salawe, int z)
throws Exception
{// this method sorts the array from the highest paid job to the lowest.
boolean swapped;// keeps track of when a swap takes place
int i;// variable fo for loop
int temp;// helps in swap
String temp2;// helps in swap
do
{
swapped = false;
for (i= 0; i < z-1; i++)// a pass through the array
{
if (salawe[i+1] > salawe[i])
// if the number before it is less they swap
{
//swap starts
temp = salawe[i+1];
salawe[i+1] = salawe[i];
salawe[i] = temp;
//swaps the jobs too if the salary is swapped
temp2 = jobestic[i+1];
jobestic[i+1] = jobestic[i];
jobestic[i] = temp2;
swapped = true;
}// end if
}// end for
} while (swapped);
}// end sorter method
public static void display(String[] jobo, int[] salary5 ,int k) throws Exception
{
//this method displays the output as a formatted table
int i;
System.out.printf("%-60s%15s%n", "Job", "Salary");
for(i=0; i<k; i++)
System.out.printf("%-60s%,15d%n", jobo[i], salary5[i]);
}
}
Please Guys, what is wrong with this code? I have racked my brain over and over and can't figure out what is wrong.... I ran this code but i keep getting errors... The errors always indicate the bolded lines. The text file I'm trying to read from is below. I want to store the job titles in one array and the corresponding salaries in the other array. Like Parallel arrays. Please what is wrong with the code? I want to store the salaries as integers because i have format it as integers when I present the output.
Thank you.
Computer and Information Research Scientists
102190
Computer and Information Analysts
80460
Computer Systems Analysts
79680
Information Security Analysts
86170
Software Developers and Programmers
87100
Computer Programmers
74280
Software Developers(Applications)
90060
Software Developers(Systems Software)
99000
Web Developers
62500
Database and Systems Administrators and Network Architects
76880
Database Administrators
77080
Network and Computer Systems Administrators
72560
Computer Network Architects
91000
Computer Support Specialists
48900
Computer User Support Specialists
46420
Computer Network Support Specialists
59090
The error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at assignment7.Coordinator.readFile(Coordinator.java:56)
at assignment7.Coordinator.main(Coordinator.java:25)
This question, or its equivalent, seems to get asked every few days.
When you call nextInt(), your scanner stops after the number. Then when you call nextLine() immediately afterwards, you're actually reading the new-line character at the end of the line that had the number on. You're not reading the next line. So on the next iteration of the loop, you're calling nextInt() when you've got non-numeric text lined up next in your scanner.
Add an extra call to nextLine() after every call to nextInt(), just to read that extra new-line character.

receiving ArrayIndexOutOfBoundsException but cannot figure out why

this is a university assignment (sample academic report), I thought I was done and going to submit but when I started testing... I keep receiving ArrayIndexOutOfBoundsException on line 60 in main and I cannot see why. I am new to Java but really put a lot of hours into this program. Any help/advice is much appreciated.
line 60 = "int credits = Integer.parseInt(input[1]);" //im thinking error is something to due with data types??? im lost.
Course / Grade / Report classes pass data to the main java2pgm1
When you call split it returns you the an array. Here you are splitting using (":")
You need to check the length of variable input before accessing it.
String[] input = course.split(":");
int credits = Integer.parseInt(input[1]);
The input array may not contain more than 1 value so it fails
The exception will occur when the input from a user does not correspond to the expected format course_number:number_of_credits:grade_received:term_taken. In your case for what input value are you running into this exception? Does it contain a :?
Suggest that you test the length of the input array before referencing index[n]
String[] input = course.split(":");
int credits = Integer.parseInt(input[1]);
Integer term = Integer.parseInt(input[3]);
Course cObject = new Course(input[0],credits,input[2],input[3]);
The above snippet in your main always assumes that the course String has abc:def:ghi:jkl atleast 3 ":" in it. It is always good practice to handle the error case, when the string doesn't have 3 ":". Modify your code to something like below
String[] input = course.split(":");
if(input.length == 4)
{
int credits = Integer.parseInt(input[1]);
Integer term = Integer.parseInt(input[3]);
Course cObject = new Course(input[0],credits,input[2],input[3]);
}
else
{
//show some error message to user
}
here size of input array may be 0 or 1, you can check it by input.length.
If size of array is less or equal the element you want to get from array then runtime exception ArrayIndexOutOfBoundsException is thrown.

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources