Working on a project for school and I'm getting a error when I try to enter the number of students for the array. The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Project1.enterStudents(Project1.java23)
at Project1.mainMenu(Project1.java59)
at Project1.enterStudents(Project1.java7)
The code I have written it below as always any help is appreciated.
import java.util.Scanner;
public class Project1{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Project1 project1 = new Project1();
project1.mainMenu();
}//main
int numOfStudents;
Student[] students = new Student[numOfStudents];
public void enterStudents(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
numOfStudents = input.nextInt();
int i;
for(i = 0; i <= numOfStudents - 1; i++){
i--;
System.out.println("Enter student's ID: ");
students[i].getId();
System.out.println("Enter student's first name: ");
students[i].getFirst();
System.out.println("Enter student's last name: ");
students[i].getLast();
System.out.println("Enter student's class: ");
students[i].getStuClass();
}
}
public void retrieveStuId(){
Scanner input = new Scanner(System.in);
System.out.println("Enter student id");
}
public void Exit(){
System.exit(0);
}
public void mainMenu(){
Scanner input = new Scanner(System.in);
System.out.println("1 - Enter student info");
System.out.println("2 - Retrieve student by ID");
System.out.println("3 - Retrieve student by last name");
System.out.println("4 - Update student");
System.out.println("5 - Exit");
int menuSelect = input.nextInt();
if (menuSelect != 1 && menuSelect != 2 && menuSelect != 3 && menuSelect != 4 && menuSelect != 5)
System.out.println("That is not a option");
else
switch (menuSelect){
case 1: enterStudents();
case 2: System.out.print("case 2");
case 3: System.out.print("case 3");
case 4: System.out.print("case 4");
case 5: Exit();
}
}
}//project1
class Student{
private int studentID;
private String firstName;
private String lastName;
private String stuClass;
public Student(){
}
public Student(int id, String first, String last, String c ){
studentID = id;
firstName = first;
lastName = last;
stuClass = c;
}
public void setID (int id){
studentID = id;
}
public void setStuClass (String c){
stuClass = c;
}
public void setFirst(String first){
firstName = first;
}
public void setLast(String last){
lastName = last;
}
public String getFirst(){
return firstName;
}
public String getLast(){
return lastName;
}
public int getId(){
return studentID;
}
public String getStuClass(){
return stuClass;
}
public String toString(){
return "Student ID: " + studentID + " ---- " + "Student Name: " + firstName + "" + lastName + " ---- " + "Class:" + stuClass;
}
}
Look at this bit of code:
for(i = 0; i <= numOfStudents - 1; i++){
i--;
System.out.println("Enter student's ID: ");
students[i].getId();
Now work out what the value of i is going to be on each line...
Why do you have the i--; line at all?
Note that this only addresses the first ArrayIndexOutOfBoundsException issue - once that's fixed, you'll end up with another ArrayIndexOutOfBoundsException because you're initializing the array before asking for numOfStudents.
Once that's addressed, you'll get a NullPointerException because you're trying to call methods via null references - you never actually create a new Student instance.
To be honest, this program is quite a long way from working - I'm not sure that Stack Overflow is going to provide the most effective teaching environment in this particular case. I would suggest you talk to your teacher and ask for some 1-on-1 tutoring.
The i--; at the top of your loop body is a likely culprit. In fact, if it wasn't causing this problem, I think it'd make your loop run forever. Why is that even there?
Also, I see another problem. When the array students is initialized, numOfStudents has not yet been assigned a value. Since it's an instance variable, it defaults to 0, which means students won't actually hold any Students.
for(i = 0; i <= numOfStudents - 1; i++){
// REMOVE THIS i--;
// i is = -1 here but Arrays start by 0
System.out.println("Enter student's ID: ");
students[i].getId();
System.out.println("Enter student's first name: ");
students[i].getFirst();
System.out.println("Enter student's last name: ");
students[i].getLast();
System.out.println("Enter student's class: ");
students[i].getStuClass();
}
Why this?
for(i = 0; i <= numOfStudents - 1; i++){
i--; //<--THIS
The problem is probably there. You are tryng to access to an array with a negative index number.
int numOfStudents is initialized to nothing.
so attempting to edit your students array will not work.
How to fix it:
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int numOfStudents = input.nextInt(); //this initializes to something.
Student[] students = new Student[numOfStudents];
then continue with your loop gathering the data.
Of course, you will want to remove the i-- as pointed out by others.
It's the i-- in your loop in enterStudents. This causes the index to go from 0 to -1 which is invalid. What exactly is this i-- supposed to accomplish?
Looks like others here have already pointed out the answer, but here's how to fish...
The fact that it's an ArrayIndexOutOfBoundsException tells you that it's happening while you're accessing an array, and it's even kind enough to tell you the index you've used that's out of bounds (in this case, -1, which is always out of bounds -- array indexes must be >= 0).
enterStudents only uses one array, and its index always comes from one variable. So, mentally step through your code and follow the values of that variable i to see if/how it can ever be -1.
Btw, for(i = 0; i <= numOfStudents - 1; i++) will work, but for(i = 0; i < numOfStudents; i++) is a bit more idiomatic.
Related
I'm trying to make a multiplayer Random Number Game on java.
I have already successfully built a single player version of this game but I'm struggling to figure out how I would skip over a user that guessed correctly in a Multiplayer setting.
The idea is that each user will take one turn at guessing their respective number stored in the array respective to their order.
If all the users are wrong it loops back again and asks them.
If a user is correct, when the "round" restarts it skips over the user that guessed correctly and continues to asks the remaining users.
Basically the scope of which I'm requesting you look is in the for loop followed by a SysOut saying "Ok " + name[i] + " Please guess a number." I hope my code is readable and any/all advice would be appreciated. Thank you!
while(run == true)
{
System.out.println("Welcome to the Random Number Game!");
System.out.print("How many players are playing?: ");
while(!sc.hasNextInt())
{
System.out.print("Incorrect format, please try again! ");
sc.next();
}
int numPlayers = sc.nextInt();
String[] name = new String[numPlayers];
int[] randomTarget = new int[numPlayers];
int[] minNum = new int[numPlayers];
int[] maxNum = new int[numPlayers];
System.out.println("What are their names?");
for(int i = 0; i<numPlayers; i++)
{
name[i] = sc.next();
}
for(int i = 0; i<numPlayers; i++)
{
System.out.print("Ok, " + name[i] + " Please select a minimum number: ");
while(!sc.hasNextInt())
{
System.out.print("Incorrect format, please try again! ");
sc.next();
}
int min = sc.nextInt();
minNum[i] = min;
System.out.print("Ok, " + name[i] + " Please select a maximum number: ");
while(!sc.hasNextInt())
{
System.out.print("Incorrect format, please try again! ");
sc.next();
}
int max = sc.nextInt();
maxNum[i] = max;
randomTarget[i] = (int) ranNum(min,max);
}
System.out.println("OK! I've picked a number for you.");
for(int i = 0; i<numPlayers; i++)
{
System.out.print("Ok, " + name[i] + " Please guess the number for me: ");
while(!sc.hasNextInt())
{
System.out.print("Incorrect format, please try again! ");
sc.next();
}
int guess = sc.nextInt();
int x=0;
int counter = 0;
int size = maxNum[i] - minNum[i] + 1;
int[] record = new int[size];
if(guess != randomTarget[i])
{
if(x<size)
{
record[x] = guess;
x++;
}
if(guess>maxNum[i] || guess<minNum[i])
{
System.out.print("ERROR: Input is not within the bounds you selected. Please try again: ");
}
if(guess>randomTarget[i] && guess<=maxNum[i])
{
System.out.println("Too high, sorry. ");
counter++;
}
if(guess<randomTarget[i] && guess>=minNum[i])
{
System.out.println("Too low, sorry. ");
counter++;
}
if(guess == randomTarget[i])
{
System.out.print("Correct!");
}
}
}
One way you could go about doing this is having an additional boolean array that is parallel to the "name" array. Start by creating a boolean array that is the same size as the "name" array:
boolean[] correctGuesses = new boolean[name.size];
If a player guesses correctly, the same index of the boolean array will be flipped to true. Before asking a player to guess, first check the corresponding index in the boolean array.
Or, consider an object-oriented approach. You could create a player class like this:
class Player {
private String name;
private boolean guessedCorrectly;
Player(String name) {
this.name = name;
guessedCorrectly = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean hasGuessedCorrectly() {
return guessedCorrectly;
}
public boolean setGuessedCorrectly(boolean guessedCorrectly) {
this.guessedCorrectly = guessedCorrectly;
}
}
For me the best to make what tou want is to use a class like failedProgrammer said.
By this way, you can first add other attributs to your player like : their scores, their names. After this you only have to use a "if" boucle to ask to each player to play or not.
I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.
I am working on a program that allows a user to add values to a 2d array and then search the array and display the value. The information is being stored properly, but all I can get to display is the animal name and not the food. Before I get grilled I've searched and implemented a bunch of different methods trying to get the correct output. I'm sure my error is pretty simple if someone could just help me understand, thanks!
/*This program will allow a user to enter information into the zoo
or search by animal for the type of food it eats*/
import java.util.Scanner;
class zoo {
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
//prompt the user to search or quit
System.out.println("Please enter the name of the animal to search for or Q to quit: ");
String animalName = in.nextLine();
animalName = animalName.toUpperCase();
if(animalName.equals("Q")){
System.out.println("Thanks for using the program!");
}
else {
searchArray(animalName);
}
return animalFood;
}
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
arrayItem = animalFood[i][j];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
}
else {
//nothing found
}
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
//constructor
public zoo() {
}
//overloaded constructor
public zoo(int x) {
int number = x;
animalFood = addArray(x);
}
//method to get users choice
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
System.out.println("Please make a choice in the menu below");
System.out.println("-------------------------\n");
System.out.println("1 - Add animals and the food they eat.");
System.out.println("2 - Search for an animal in the zoo.");
System.out.println("3 - Exit the program");
selection = input.nextInt();
return selection;
}
//main method
public static void main(String[] args) {
//create a new object
zoo myZoo = new zoo();
//variables and scanner
int userChoice;
int numberAnimals;
String animalName = "";
Scanner input = new Scanner(System.in);
//call the menu
userChoice = menu();
//actions based on user choice
if (userChoice == 1) {
System.out.println("How many animals would you like to enter information for?");
numberAnimals = input.nextInt();
myZoo.addArray(numberAnimals);
}
if (userChoice == 2) {
System.out.println("Please enter the name of the animal to search for: ");
animalName = input.nextLine();
myZoo.searchArray(animalName);
}
if (userChoice == 3) {
System.out.println("Thank you for using the program!");
}
}
}
It looks to me like your problem is in searchArray. Your nested for loops are iterating over the size of only one dimension of the array:
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
...
}
}
Replace animalFood.length with animalFood[i].length, like you did correctly in the addArray method.
EDIT
It also looks like your output method is incorrect.
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
In this line, animalFood[j] should be animalFood[i][j]. The strange output you're seeing is Java's attempt at converting an array into a String.
2nd Edit
After examining the addArray method, it seems I've made an incorrect assumption about your array. It appears your array is structured such that each index has 2 items, the animal, and its food. So it looks like so:
animalFood[0][0] = 'Cat'
animalFood[0][1] = 'Cat food'
animalFood[1][0] = 'Dog'
animalFood[1][1] = 'Dog food'
etc.
If this is the case, then you're going to want to change your loop to only iterate over the outer index. This means removing the inner for loop inside of searchArray. Then, you're only going to compare the first index of the inner array to the item you want to match, and if there's a match, then the food will be the second index. I'll leave implementation up to you (since this looks like a homework question). If something I've said here sounds wrong, let me know.
So I'll give you some brief background, I'm in AP computer science and I'm confused on this program.
We are suppose to enter in the size of the array, then the program runs through a for loop, get the full name in one string, ( use scanner.nextLine();), then the test Score, which isn't that important. The user then will enter the first name of ANYONE and there should be a for loop running through each array seeing if firstName is in the first name array.
The problem is firstName when is printed out is blank.. fixed the first error.
import java.util.Scanner;
public class totalScores {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int sizeOfArray = input.nextInt();
String kline[] = new String[sizeOfArray];
for ( int index= 0; index< kline.length; index++)
{
System.out.println("Enter the name: ");
String name = input.next();
kline[index]= name;
input.nextLine();
}
double[] testScore= new double[sizeOfArray];
for (int i = 0; i< testScore.length; i++)
{
System.out.println("enter the test score");
double testz = input.nextDouble();
testScore[i]= testz;
input.nextLine();
}
System.out.println("Enter first name : ");
String want = input.next();
for( int index = 0; index < kline.length; index++)
{
String firstName="";
String namez;
namez = kline[index];
int space = namez.indexOf("");
firstName = namez.substring(0,space);
if (want.equalsIgnoreCase(firstName))
{
System.out.println("The test score is: "+ testScore[index]);
}
else
{
System.exit(0);
}
}
}
}
Your example is not too clear but I can see the for loop is running with kline.length as the limit, but you are getting nameofarray[index] which could be an array with different size than kline.
Possibly the problem is here:
int space = namez.indexOf(" ");
In case the namez don't contain spaces in it, the value for space will be -1. So it will form this statement:
namez.substring(0, -1)
Of-course you will encounter exception.
Try doing this:
String firstName = kline[index].split(" ")[0];
System.out.println(firstName);
This will return the first word of kline[index] even if it doesn't contain a space.
The error is occurring most likely because your kline[index] does not contain a space (therefore, indexOf(" ") returns -1. And you cant substring with (0,-1)
I am trying to use a menu system that can delete a customer from my array myHotel[], this is built from an object.
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
...
public void deleteCustomer(String myHotel[]){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
roomNum=input.nextInt();
myHotel[roomNum].setName("e");
}
I get the errors, cannot find symbol?
Here is the Full Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int roomNum=0;
Room[] myHotel = new Room[10];
for (int x =0; x<10; x++){
myHotel[x] = new Room();
}
String roomName;
String menu;
do {
System.out.println("Please Select an Option from the Menu:");
System.out.println("Enter V to View all Rooms");
System.out.println("Enter A to Add Customer to Room");
System.out.println("Enter D to Delete Customer from Room");
System.out.println("Enter Q to Quit");
menu=input.next();
//if(menu.charAt(0) == 'V')viewAllRooms();
//if(menu.charAt(0) == 'A')addCustomer();
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
} while (menu.charAt(0) != 'Q');
while (roomNum < 10) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
for (int x = 0; x < 10; x++) {
//System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
}
public void deleteCustomer(String myHotelRef){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
int deleteRoom=input.nextInt();
myHotelRef[deleteRoom].setName("e");
}
}
You get multiple errors. What is myHotel[]? roomNum is not defined, etc.
Please use your compiler.
Also: please read https://stackoverflow.com/help/how-to-ask :-)
First you need declare myHotel array and pass it with out [].
deleteCustomer(myHotel);
Second, there is not such a method setName(String name) in String class
myHotel[roomNum].setName("e");// no such a method
Third, you need to declare the roomNum variable like:
int roomNum = input.nextInt();
Your main problem is that you've included [] in your call to deleteCustomer. It should be:
if (menu.charAt(0) == 'D') {
deleteCustomer(myHotel);
}
When you reference an array object as a whole you don't include square brackets. Square brackets are for the declaration, initialisation and for accessing individual elements within the array.
I'd also recommend that you get into the habit of always using curly braces with your if, for and while constructs, as not including them is often the cause of bugs. It also makes it easier to read when you come back to it, and you're clearly indicating to others what should be part of the loop and what shouldn't.