How to solve java.util.InputMismatchException - java

I'm working on a java lab and the first step is reading data from the input text file. I've been trying to fix the code but it doesn't help at all. Could you guys please take a look and let me know what I can do about it?
The error I get is:
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.nextDouble(Scanner.java:2456)
at Restaurant.<init>(Restaurant.java:35)
at RestaurantTester.main(RestaurantTester.java:11)
For the tester class with main method
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class RestaurantTester {
private static Scanner buffer = new Scanner(System.in);
private static int inputInt;
private static Restaurant restaurant;
public static void main(String[] args) throws FileNotFoundException {
restaurant = new Restaurant();
System.out.print("\n Welcome to Java Restaurant\n");
System.out.print("\n\n*************************************\n");
System.out.print("1. Display Menu\n");
System.out.print("2. Display Server List\n");
System.out.print("3. Restaurant Activities\n");
System.out.print("4. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
while (inputInt != 4) {
switch (inputInt) {
case 1: {
restaurant.displayMenu();
break;
} // end case 1
case 2: {
restaurant.displayServerList();
break;
} //end case 2
case 3:{
System.out.print("\n\n*************************************\n");
System.out.print("1. Restaurant Activity\n");
System.out.print("2. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
while (inputInt != 2) {
restaurant.restaurantActivity();
System.out.print("\n\n*************************************\n");
System.out.print("1. Restaurant Activity\n");
System.out.print("2. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
} // end inner while
break;
} // end case 3
} // end switch
System.out.print("\n\n*************************************\n");
System.out.print("1. Display Menu\n");
System.out.print("2. Display Server List\n");
System.out.print("3. Restaurant Activities\n");
System.out.print("4. Quit\n");
System.out.print("*************************************\n");
System.out.print("Enter choice: ");
inputInt = buffer.nextInt();
} // end outer while
System.out.print("\nThank you. The Java restaurant is now closed.\n");
} // end main
}
For my Restaurant class
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Restaurant {
...
private Menu menu;
public ArrayList<Server> servers;
private Activity activity;
public Restaurant() throws FileNotFoundException {
input = new Scanner(new File("menu.txt"));
menu = new Menu();
servers = new ArrayList<Server>();
temp = input.nextLine(); // skip 1st line
for (int index = 0; index < 3; index++) {
servers.add(new Server(input.next(), (input.nextLine()).split(",",6)));
} // assume only 6 tables for each server
temp = input.nextLine(); // skip instruction line
while (input.hasNext()) {
str1 = input.next();
str2 = input.next();
value = input.nextDouble();
menu.setMenuItem(str1,str2, value);
}
} // end constructor
....
}
And heres my text file:
Waiters: first name followed by table list
John 1,2,5,9,11,15
Maria 3,4,6,7,17,18
Mike 8,10,12,13,14,26
Menu: listing of the full menu: item code, name, price
A1 Bruschetta 5.29
A2 Caprese_Flatbread 6.10
A3 Artichoke-Spinach_Dip 3.99
A4 Lasagna_Fritta 4.99
A5 Mozzarella_Fonduta 5.99
E1 Lasagna_Classico 6.99
E2 Capellini_Pomodoro 7.99
E3 Eggplant_Parmigiana 8.99
E4 Fettuccine_Alfredo 7.49
E5 Tour_of_Italy 14.99
D1 Tiramisu 2.99
D2 Zeppoli 2.49
D3 Dolcini 3.49
S1 Soda 1.99
S2 Bella_Limonata 0.99
S3 Berry_Acqua_Fresca 2.88

You need to skip one more line.
Skip one
read three
skip blank line?
skip instructions
loop till the end
From http://www.java-made-easy.com/java-scanner-help.html:
Q: What happens if I scan a blank line with Java's Scanner?
A: It depends. If you're using nextLine(), a blank line will be read in as an empty String. This means that if you were to store the blank line in a String variable, the variable would hold "". It will NOT store " " or however many spaces were placed. If you're using next(), then it will not read blank lines at all. They are completely skipped.
My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")

I may be wrong, but it seems you need to skip two lines after finishing the first portion of the file. You skip one line, but that may just be the line space. So you need to skip again to get to your desired content. Try adding another nextLine()
input.nextline();
temp = input.nextLine();
Also, it's possible you may have a problem with the scanner not going to next line after nextDouble(). If the above didn't work, Try adding a nextLine() after it and see if that works?
value = input.nextDouble();
input.nextLine();
Consider even using a split to avoid this problem
while (input.hasNextLine()) {
String line = input.nextLine();
String[] token = line.split("\\s+");
str1 = tokens[0].trim();
str2 = tokens[1].trim();
value = Double.parseDouble(tokens[2].trim());
menu.setMenuItem(str1,str2, value);
}
The above code will read each line, line by line, then split the three into an array of Strings. The last value will need to be parsed into a double.
Edit: Here's another
servers.add(new Server(input.next(), (input.nextLine()).split(",",6)));
You're reading the next, then the nextLine. You need to read all in one line
Edit: try this code
public Restaurant() throws FileNotFoundException {
input = new Scanner(new File("menu.txt"));
menu = new Menu();
servers = new ArrayList<Server>();
temp = input.nextLine(); // skip 1st line
for (int index = 0; index < 3; index++) {
String line = input.nextLine();
String[] tokens = line.split("[\\s,]+");
String name = tokens[0];
String[] nums = new String[6];
for (int i = 1; i < tokens.length; i++) {
nums[i - 1] = tokens[i].trim();
}
servers.add(new Server(name, nums));
} // assume only 6 tables for each server
input.nextLine();
temp = input.nextLine(); // skip instruction line
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split("\\s+");
str1 = tokens[0].trim();
str2 = tokens[1].trim();
value = Double.parseDouble(tokens[2].trim());
menu.setMenuItem(str1,str2, value);
}
}

Related

Check if characters in a firstname String contain at least 1 digit

I try to check if characters in a firstname String contain at least 1 digit, if yes ask to the user to input it again and then going back to the loop and check again but with a GoTo break it only works the first time and won't loop it again. Oh and I do this from a method with a String array of more than only a first name in it. Isn't the break GoTo supposed to bring me back to my label and then do the loop over again looking for a digit?
public static void main(String[] args) {
infoInputGathering();
}
public static String[] infoInputGathering(){
String[] infos = new String[3]; // Declaration of the infos String array
boolean isStringOnly;
char[] characterChecker;
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
// Asking the user to input their first name and stores it in a String Array info[0]
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
firstname:
for (int c = 0 ; c<=characterChecker.length ; ++c ) {
if (Character.isDigit(characterChecker[c])) {
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
Break firstname;
}
}
Final Full Code I came up with with Ali's help on this part
import java.util.Scanner;
import java.util.ArrayList;
public class InfiniteInfoGatheringUntilStop {
public static void main(String[] args) {
int iterationsCounter = 0; // Declares/Initiate a counter for the loops
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
ArrayList<String> names = new ArrayList<String>(); // Creates an ArrayList for the names inputs
ArrayList<String> birth = new ArrayList<String>(); // Creates an ArrayList for the date of birth inputs
ArrayList<String> gpa = new ArrayList<String>(); // Creates an ArrayList for the GPA inputs
while(true){ // Always true loop unless break out on if conditions
System.out.print("Enter your name: ");
names.add(input.next());
//Code to check if there are numerical character in the String of the listArray inputted
char[] characterChecker = names.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
int c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as numerical
if(Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
names.set(iterationsCounter,input.next());
characterChecker = names.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){
break;
}
}
if(names.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
break;
}
System.out.print("Enter your date of birth in this format AAAAmmdd: ");
birth.add(input.next());
characterChecker = birth.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 8){ // Checks for a maximum length of 8 characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checkes if there are letters in the characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(birth.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
break;
}
System.out.print("Enter your GPA in 0.0 format: ");
gpa.add(input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 3){ // Checkes for a maximum length of 8 characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA please: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checks if there are digits in the characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(gpa.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
gpa.remove(iterationsCounter);
break;
}
iterationsCounter++; // Incrementes the counter if a full loop is done
}
// Prints the results
System.out.println("Number of valid inputs before you got exhausted: " + iterationsCounter);
System.out.println("====================================================================================");
//A loop to print the content of the 3 ListArrays
for(int arrayLoc = 0; arrayLoc < iterationsCounter; arrayLoc++){
System.out.println((arrayLoc+1) + "-\t" + names.get(arrayLoc) +
"\t\t" + birth.get(arrayLoc) +
"\t\t" + gpa.get(arrayLoc));
}
}
}
You can write your code with while loop like this:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] infos = new String[3];
char[] characterChecker;
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
int c = 0;
while(true){
if (Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
c = 0;
}
else
c++;
if(c == characterChecker.length)
break;
}
System.out.println("Correct Name");
}
}
If c is equal to characterChecker.length, ie in the name, there is no number, then it is correct and we break loop and print Correct Name.

Read columns from .txt file

I have a text file (archive.txt) which has 9 columns of data separated by a tab. I want to read the columns and perform simple math.
In the example below, I want to find the average cost(iCost) by adding all policies with high (3) or unlimited (4) in column cData then dividing by the total of high and unlimited. High and unlimited are represented by a 3 and 4, respectively, in the archive file.
There are two System.out.println() numbered 1 and 2. They are used to see where the program gets to. It doesn't make it past the first System.out.println.
public int highUnlimited() {
Scanner input = new Scanner(System.in);
input = new Scanner("archive.txt");
int iLargeBundle = 0;
int iCost = 0;
System.out.println("1");
String cDate = input.next();
int cMinutes = input.nextInt();
int cData = input.nextInt();
int cLength = input.nextInt();
boolean cIntCalls = input.nextBoolean();
String cReference = input.next();
int cCostPerMonth = input.nextInt();
String cFirstName = input.next();
String cSecondName = input.next();
System.out.println("2");
if (cData == 3 || cData == 4) {
iLargeBundle = iLargeBundle++;
iCost = iCost + cCostPerMonth;
}
int iTotal = iLargeBundle / iCost;
return iTotal;
}
These are the first two lines of the Archive file. They don't have headings normally
15-Sep-2016 2 1 12 N MT230N 617 C Clark
25-Oct-2016 1 1 12 N ED641N 475 Z Clark
input = new Scanner("archive.txt");
This opens up a scanner on the string "archive.txt", not a file with that name.
If you wish to scan a file, you will need to do the following:
input = new Scanner(new File("archive.txt"));
Here you have your code rewritten with comments showing you how to do it, i've added a loop in case you want to read all the lines of the file you are able to do it (in that loop i added the methods hasNextLine(), returns true if there is a line next and nextLine(), it jumps to the next line). It is important that you import java.io.; to import the class file and import java.util.; to import that class Scanner. I hope i could help you.
public int highUnlimited(){
try{ //you all ways need to try catch the Exceptions when you use Scanner and File.
File f = new File("path"); //We need to create first the file object this is
//done with the constructor File(String path)
Scanner input = new Scanner(f); //You dont need the Scanner.in, the Scanner.in
//scanns input data from the terminal and we want
//to scann it from a File. Th constructor
//Scanner(String path) that you used doesn't exist
//on java.
int iLargeBundle = 0;
int iCost = 0;
String cDate, cReference, cFirstName, cSecondName; // I declare the variables outside so there
int cMinutes, cData, cLength, cCostPerMonth; //is no problem with the while
boolean cIntCalls;
int iTotal = 0; //I've used 0 as default value for iTotal
System.out.println("q");
while(input.hasNextLine()){ //I use hasNextLine in case you have various lines of data in your file
cDate = input.next();
cMinutes = input.nextInt();
cData = input.nextInt();
cLength = input.nextInt();
cIntCalls = input.nextBoolean();
cReference = input.next();
cCostPerMonth = input.nextInt();
cFirstName = input.next();
cSecondName = input.next();
input.nextLine(); //To jump a line so it doesn't block on the while
if (cData == 3 || cData ==4){
iLargeBundle++; //if you only want to add 1 to the variable with this is enough
iCost = iCost + cCostPerMonth;
}
}
iTotal = iLargeBundle/iCost; //as iCost is = if it hasn't been modified here is going
//to show an error because you can't divide by 0 so you have
//to change this in cas iCost is 0
}
catch(Exception e){
System.out.println(e.getMessage());
}
return iTotal;
}

Using BufferReader to get input from User

So when I run my program's main method it prints:
Enter number of test cases:
1
Enter string 1
Enter string 2
rat apple cat ear cat apple rat
For some reason it prints Enter string 1 and Enter string 2 before I even put in anything for String one. Can anyone shed any light as to why this is happening. Is there something wrong with the way I have the BufferReader setup?
Code:
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of test cases: ");
int testcases = in.read();
System.out.println("Enter string 1");
String[] str1 = in.readLine().split(" ");
System.out.println("\nEnter string 2");
String[] str2 = in.readLine().split(" ");
for(int i = 0; i < testcases; i++)
{
String result = lcss(str1, str2);
System.out.println("\nLCSS: "+ result);
System.out.println("\nLCSS Length = "+ result.length());
}
}
Please use the following.
int testcases = Integer.valueOf(in.readLine());
Read more on BufferedReader.read()
int testcases = in.read(); doesn't read the line break (when you press Enter).
The readLine() in the line String[] str1 = in.readLine().split(" "); will now begin to read directly after the number you entered and search for the next line break. The line break from you entering the number is now found and the function directly returns without waiting for your input.
So much for the explanation on what causes your program to behave the way it does.
Now you do have another error, as BufferedReader.read() doesn't do what you think it does. Check the documentation
So when you enter a 1 your testcases varaible will contain the UTF-16 value of the character '1' which is 31.
As other answers already pointed out you should either use Integer.valueOf(in.readLine()); to get the value for testcases or use Scanner
EDIT:
Get the number of test cases as integer
Create a 2 dimensional array to store test cases. First dimension holds each test case & second dimension holds String[] of word list in each test case.
Iterate through "for loop" until you get each test case string array for total number of test cases,
Sample code:
public static void main(String[] args) throws Exception
{
Scanner in = new Scanner(System.in);
System.out.println("Enter number of test cases: ");
int testcases = in.nextInt();
System.out.println("test cases:"+testcases);
String[][] strs = new String[testcases][];
for ( int i =0; i< testcases ; i++ ){
System.out.println("Enter string:"+i);
in = new Scanner(System.in);
if (in.hasNext()) {
String s = in.nextLine();
System.out.println(s);
strs[i] = s.split(" ");
System.out.println("Length:"+strs[i].length);
}
System.out.println();
}
// Add your logic
}

While loop with hasNext(); not fully looping

I'm in the process of creating a program that reads data from an external file, compares it with other data within the file then prints the results to a new external file. I am having problems with the while loop section of my code. I am unsure whether it is the while loop itself or the for loop which is nested within. Here is the code:
public class WageCalculator {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
PrintWriter output = new PrintWriter("wagedaily.txt");
float RecommendedMaximum;
RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter the recommended maximum journey cost:"));
String ShipID, JourneyID; //Variables
int JourneyLength, Crew;
double RateOfPay, CrewCost, TotalCost;
while (input.hasNext()) { //EOF-Controlled While Loop
ShipID = input.nextLine();
JourneyID = input.nextLine();
JourneyLength = input.nextInt();
Crew = input.nextInt();
CrewCost = 0; //Default Values Set
TotalCost = 0;
for (int x = Crew; x > 0; x--) { //For Loop updates the above values
RateOfPay = input.nextDouble();
CrewCost = RateOfPay * JourneyLength;
TotalCost = TotalCost + CrewCost;
}
if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
System.out.println("The total cost of...");
output.println("The total cost of...");
} else if (TotalCost == RecommendedMaximum) {
System.out.println("The total cost of...");
output.println("The total cost of...");
} else {
System.out.println("The total cost of...");
}
}
output.close(); //Close both Scanner and Printwriter
input.close();
}
}
The error I get is this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at (package).WageCalculator.main(WageCalculator.java:30)
The error says it's line 30 in my code that is the problem but I am not so sure.
Incase anyone needs to see the TestData.txt file:
Monarch //ShipID
M141 //JourneyID
16 //JourneyLength
6 //Crew
10.5 //RateOfPay -
10.5
20
20
20
30 //- RateOfPay
Princess //ShipID
P103 //JourneyID
18 //JourneyLength
5 //Crew
40 //RateOfPay -
45
45
60
80 //- RateOfPay
Any help would be appreciated :)
You're making a bunch of input.nextXXX() calls within the loop after checking input.hasNext() only once at the top of the loop. Don't do that as this is very unsafe and bound to fail and as there should always be a one-to-one correspondence between a check and a get. For instance, if you want to get a next line, there should be one input.HasNextLine() called before calling calling input.nextLine(). Same for input.next() or input.nextInt().
Myself, I'd read line by line by checking hasNextLine() and then once reading in the nextLine(), and then manipulating the String received.
while (input.hasNextLine()) {
String line = input.nextLine();
// now do not use input further within the loop
}
You could then within the loop use a second Scanner using the line received, or split the line via String#split(String regex) or do whatever you need to do with it.
Or you could use String replaceAll(...) and regular expressions to get rid of all white space followed by "//" followed by any chars. e.g.,
while (input.hasNextLine()) {
String line = input.nextLine();
// get rid of white space followed by "//" followed by anything
line = line.replaceAll("\\s+//.*", "");
System.out.println(line);
}
Edit
I've looked a bit more into your question and your data, and I am going to amend my answer. If you're absolutely sure of the integrity of your data file, you could consider checking for nextline once per obtaining data of an entire ship. For example:
public static void main(String[] args) {
InputStream inStream = GetData.class.getResourceAsStream(DATA_FILE);
List<Cruise> cruiseList = new ArrayList<>();
Scanner input = new Scanner(inStream);
while (input.hasNext()) {
String name = getLine(input);
String id = getLine(input);
int length = Integer.parseInt(getLine(input));
int crew = Integer.parseInt(getLine(input));
// assuming a class called Cruise
Cruise cruise = new Cruise(name, id, length, crew);
for (int i = 0; i < crew; i++) {
cruise.addPayRate(Double.parseDouble(getLine(input)));
}
cruiseList.add(cruise);
}
input.close();
}
private static String getLine(Scanner input) {
String line = input.nextLine();
// get rid of white space followed by "//" followed by anything
line = line.replaceAll("\\s+//.*", "");
return line;
}
The reason it gives you trouble is because when the user enters an integer then hits enter, two things have just been entered - the integer and a "newline" which is \n. The method you are calling, "nextInt", only reads in the integer, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you had to call nextLine() before your code would work. You could have also called next(), which would also have read in the newline.
Also read the Documentation of Scanner class for further understanding :
Here is the Corrected Code :
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class WageCalculator {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("TestData.txt")); //Scanner for external file
PrintWriter output = new PrintWriter("wagedaily.txt");
float RecommendedMaximum;
RecommendedMaximum = Float.parseFloat(JOptionPane.showInputDialog(null,
"Enter the recommended maximum journey cost:"));
String ShipID, JourneyID; //Variables
int JourneyLength, Crew;
double RateOfPay, CrewCost, TotalCost;
while (input.hasNext()) { //EOF-Controlled While Loop
System.out.println("While Enter"); // For debugging purpose
ShipID = input.nextLine();
JourneyID = input.nextLine();
JourneyLength = input.nextInt();
input.nextLine(); // Enter this to read the data of skipped Line
Crew = input.nextInt();
input.nextLine();
CrewCost = 0; //Default Values Set
TotalCost = 0;
for (int x = Crew; x > 0; x--) { //For Loop updates the above values
System.out.println("While Under if Enter");// For debugging purpose
RateOfPay = input.nextDouble();
input.nextLine();
CrewCost = RateOfPay * JourneyLength;
TotalCost = TotalCost + CrewCost;
System.out.println("While Under if Exit");// For debugging purpose
}
if (TotalCost < RecommendedMaximum) { //if-else statements to compare values
output.println("The total cost of...");
} else if (TotalCost == RecommendedMaximum) {
System.out.println("The total cost of...");
output.println("The total cost of...");
} else {
System.out.println("The total cost of...");
}
System.out.println("While Exit"); // For debugging purpose
}
output.close(); //Close both Scanner and Printwriter
input.close();
}
}

2D Array's & Out of bounds exceptions

I hate Arrays
So I've been doing some coding and I've come up with an error (out of bounds exception) that I just can't seem to fix. I believe where I am saying 'array1[counter2][counter] = input2.nextLine();' is the problem but I don't know what is wrong! Help, I can't stand these Out of Bounds exceptions
The Idea for the program is an online phone book that you can add contacts, view them, and search by their first name, surname, and phone number.
Here's the code I'm using:
import java.util.Scanner;
import java.awt.*;
public class testMattWalker {
//
public static void main (String[] args){
//Declare all your variables here. Make sure to provide a comment explaining the purpose of each variable
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
int counter = 0;
int counter2 = 0;
boolean go = true;
//Temp VAriables for entry
String firstNameOfEntry = "";
String lastNameOfEntry = "";
String personPhoneNumber = "";
//
//create array
String [][] array1 = new String[5][3];
while (go) {
String choice = "";
System.err.println("\n\n\n\n\n\n\n\n\nDIDGITAL PHONE BOOK 2013");
System.out.println("1- Create phone book\n2- Display phone book\n3- Find person(s) by last name\n4- Find person(s) by first name\n5- Find person(s) by phone number\n6- Exit application");
choice = input.nextLine();
if (choice.equals("1") && counter2 != 6) {
System.err.println("\n\n\n\n\nPHONE BOOK ENTRY CREATOR:");
System.out.println("Please enter the first name of the person you wish to enter: ");
array1[counter2][counter] = input2.nextLine();
counter++;
System.out.println("Please enter the last name of the person you wish to enter: ");
array1[counter2][counter] = input3.nextLine();
counter++;
System.out.println("Please enter the phone number of this person: example:9057773344");
array1[counter2][counter] = input4.nextLine();
counter++;
counter2++;
}else if (choice.equals("2")) {
}else if (choice.equals("3")) {
}else if (choice.equals("4")) {
}else if (choice.equals("5")) {
}else if (choice.equals("6")) {
}
}
}// end of main
}// end of class
I know it's not close to done but I'm the kind of guy who likes to fix everything before moving on so any help would be appreciated! (:
You set the second dimension of your array as 3, but in your code you add 1 to counter 3 times, meaning it goes out of bounds of the array after the first iteration of the code.
As ljgw said array indexes start at 0, so a dimension of 3 means the corresponding indexes are 0,1 and 2.
Remember that array indexes start with 0. So: 5 is already out-of-bounds for counter2.

Categories