2D Array's & Out of bounds exceptions - java

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.

Related

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

java array that accepts input of put name mark, quit and get name (not working)

im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

Expanding my program

So i got a programm that asks the user to type in the 3 favorite cities ,
it stores them in Array and prints them later out to the user. What im trying to do now is
making the programm ask the user for how many favorite cities he/she got?the user types in
a number wich will give the user the oppertunity to type in that ammount of favorit cities
and later on print them out.
Problem is i really have no idea how to do this could anyone help?
Please explain the code incase you help so i can understand :) , Sorry for my bad English not my
primary language!
My code atm looks like this :
package com.example.array.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String[] favoritCity = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String userIn1 = scanner1.nextLine();
String userIn2 = scanner1.nextLine();
String userIn3 = scanner1.nextLine();
favoritCity[0] = userIn1;
favoritCity[1] = userIn2;
favoritCity[2] = userIn3;
System.out.println(userIn1);
System.out.println(userIn2);
System.out.println(userIn3);
}
}
First take a integer input from user, that how many favorite cities does he/she have?
Scanner#nextInt(); which could help you get integer input from console. Create a array with that size Then write loop like -
String[] favoritCity = new String [noOfFabCities];
for(int i=0;i<maxFavCities;i++){
...
}
Now inside the loop get the input from user Enter your i+1 (as i starts with 0) favorite city and capture the input like Scanner#nextLine();. and keep the value into your array like -
favoritCity[i] = userInput;
Once you get all the user input, now can you print in console all the user's favorite cities.
That should be the code which are you looking for. I don't tested it, but it should works.
package com.example.array.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
int cityNumb;
Scanner scanner1 = new Scanner (System.in);
System.out.println("How many favorite cities do you have?");
cityNumb = scanner1.nextInt();
//creat the array with the size of cityNumb
String[] favoritCity = new String [cityNumb];
System.out.println("skriv in "+cityNumb+" favoritstäder");
//for loop for the input of the cities
for(int i = 0; i < cityNumb; i++)
{
String city = scanner1.nextLine();
favoritCity[i] = city;
}
//for loop for the output of the cities
for(int i = 0; i < cityNumb; i++)
{
System.out.println(favoritCity[i]);
}
}
}
Before to define your Array size, you can use your scanner to ask for the number of cities, for example:
Scanner scanner = new Scanner(System.in);
System.out.println("How many cities?");
int nberCities = scanner.nextInt();
String[] favoriteCities = new String[nberCities];
for(int i = 0; i < nberCities;i++){
favoriteCities[i] = scanner.nextLine();
}

not printing my code in if /else statement

So im creating jeapordy in java, and i dont care that i spelt it wrong(if i did) but i only have one question coded so far with only one answer, and it asks the question but only prints out you are wrong even if the answer is right.
it is asking the first history question and the answer is george, but it is printing out that the answer is wrong. the first history question is also worth 100. i have not began to code the math part yet.
thanks if you can help fin my problem! its probably really simple as i am a beginner.
import java.util.Random;
import java.util.Scanner;
public class game {
public static void main (String[] args){
//Utilites
Scanner s = new Scanner(System.in);
Random r = new Random();
//Variables
String[] mathQuestions;
mathQuestions = new String[3];
mathQuestions[0] = ("What is the sum of 2 + 2");
mathQuestions[1] = ("What is 100 * 0");
mathQuestions[2] = ("What is 5 + 5");
String[] historyQuestions;
historyQuestions = new String[3];
historyQuestions[0] = ("What is General Washingtons first name?");
historyQuestions[1] = ("Who won WWII, Japan, or USA?");
historyQuestions[2] = ("How many states are in the USA?");
//Intro
System.out.println("Welome to Jeapordy!");
System.out.println("There are two categories!\nMath and History");
System.out.println("Math History");
System.out.println("100 100");
System.out.println("200 200");
System.out.println("300 300");
System.out.println("Which category would you like?");
String categoryChoice = s.nextLine();
System.out.println("For how much money?");
int moneyChoice = s.nextInt();
if (categoryChoice.equalsIgnoreCase("history")){
if (moneyChoice == 100){
System.out.println(historyQuestions[0]);
String userAnswer = s.nextLine();
s.nextLine();
if (userAnswer.equalsIgnoreCase("george")){
System.out.println("Congratulations! You were right");
}
else{
System.out.println("Ah! Wrong answer!");
}
}
}
}
}
When you call nextInt(), a newline character is left unread, so a subsequent call to nextLine() will return an empty string (since it reads up to the end of the line). Call newLine() once prior to read/discard this trailing newline:
if (moneyChoice == 100) {
System.out.println(historyQuestions[0]);
s.nextLine(); // <--
String userAnswer = s.nextLine();
System.out.println(userAnswer);
...
As an aside, don't forget to close your Scanner when you're finished with it: s.close().
int moneyChoice = s.nextInt(); reads only the integer. It leaves a newline pending reading. Then String userAnswer = s.nextLine() ; reads an empty line that is obviously different from "george". Solution: read the newline immediately after the int, and do so in the whole program. You could prefer to create your own method nextIntAndLine().
int moneyChoice= s.nextInt() ;
s.nextLine();

Categories