I have two classes that basically function as the most simplest database, where the user is supposed to enter a string and the program adds it in the array using a class that holds all the methods. Except that when i enter the first name it gives me java.lang.ArrayIndexOutOfBoundsException: 0. I know this means that no memory is being allocated for the array but i thought i did this in my second class where there is a constructer that defines the size of the array. Im not experienced enough with arrays to fix this debug on my own. Much help would be appreicated!
import java.util.*;
public class TestDatabase {
//contant value for data base 'size' of array
public static final int constant = 10;
public static void main (String[] args){
//Database object sets the array size to constant value
Database get = new Database(constant);
//input stream
Scanner in = new Scanner (System.in);
//varaibles for the count and index; prompt
int count = 0;
int index = 0;
System.out.println("Please enter 10 names to add them to the database. Name: " + (count += 1));
//while the count is lower than or equal to 10...
while(count<=10){
//input stream equal to input
String input = in.nextLine();
//if the count equals, stop the loop
if (count == 10)
{
//breaks the loop
break;
}
//prints out the current name
System.out.print(" Name: " + (count +=1));
//adds the input to the array
get.add(index,input);
//increments index by 1
index++;
}
//prints the array
get.print();
}
}
Here is my class with my all my methods:
import java.util.*;
public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
_size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
//the values of string is placed into some index of the array
userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
//prints array
System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
//sorts the array
Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
Arrays.asList(userArray).contains(value);
}
}
Your ArrayList is never instantiated properly, you need to move it into your constructor so when the new operator is called, then the arraylist is created with the size variable that is passed, so something like this:
public Database {
private String[] data;
public Database(int size){
this.data = new String[size];
}
}
With your current code, the array is created before the size is actually given, so it defaults to a size of 0.
userArray init with zero length before your constuctor set _size. Create userArray in constructor.
there next steps performed when you create class:
_size init with 0
userArray init with zero length array
_size init with size value.
Change the code as below
String[] userArray;
public Database(int size){
_size = size;
userArray = new String[_size];
}
Related
My code is supposed to print out the student with the highest range. There is a method in my Student class which calculates the range, while in my Classroom class there is another method that determines which student had the highest growth. My problem comes in the class Student, I get an Out of Bounds Exception in the addExamScore method.
Main class:
public class ClassroomTester
{
public static void main (String[] args)
{
Classroom c = new Classroom(2);
Student ada = new Student("Ada", "Lovelace", 12);
ada.addExamScore(44);
ada.addExamScore(65);
ada.addExamScore(77);
Student alan = new Student("Alan", "Turing", 11);
alan.addExamScore(38);
alan.addExamScore(24);
alan.addExamScore(31);
c.addStudent(ada);
c.addStudent(alan);
c.printStudents();
Student mostImproved = c.getMostImprovedStudent();
System.out.println("The most improved student is " + mostImproved.getName());
}
}
Student class:
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[numExamsTaken];
numExamsTaken = 0;
}
public int getExamRange()
{
int maximum = 0;
int minimum = 0;
for(int i = 0; i < exams.length; i++){
if(exams[i]<exams[minimum]){
minimum = i;
}
else if(exams[i]>exams[maximum]){
maximum = i;
}
}
return exams[maximum]-exams[minimum];
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
First, you're initializing exams in the constructor the line before you initialize numExamsTaken, the order should be reversed because you need to know what numExamsTaken is before using it. I'd recommend storing the maximum and minimum as scores instead of indexes but that's just personal preference I think it makes the code more readable, so up to you. The index out of bounds problem probably has to do with your addExamScore method. If you've taken 4 exams it might look like [90, 85, 74, 82] where the indexes are 0, 1, 2, 3 and numExamsTaken = 4. Indexes starting at 0 is called zero-indexing and is used in most if not all programming languages.
exams[3] = 82 and exams[4] is going to give you an out of bounds error. Since you're not using an arrayList every time you want to add an element you're going to need to create an empty array of one size bigger than your current array, copy the previous scores over, and slide the new score into the last slot (in the case above would be index 4, which isn't out of bounds in the new array). Store your new array where your old array was in exams[].
Index out of bounds exception shows when array crosses it limits to store the value.
You have declared array of size '0' inside the constructor
in the line exams = new int[numExamsTaken];
initialize the size of the array with your expected range or use ArrayList to add values without specifying the size in prior
The problem with your code here is that you are trying to access a value in an array, which has not been allocated there. This is why the output is giving a ArrayIndexOutOfBoundsException, since you are trying to access an index in an array that is out of bounds of the array. In Java, arrays are fixed in size, meaning once you call new on an array, you cannot change the size of it without calling new on another array with a different size. In this case, it will be easiest to use a List, like an ArrayList, which does all of the resizing, copying, etc. for you, so you can use it as if it were a dynamically sized array. Your code would change to look something like this:
public class Student
{
// ...
private List<Integer> exams;
// ...
public Student(String fName, String lName, int grade)
{
// ...
exams = new ArrayList<>();
// ...
}
public int getExamRange()
{
int maximum = 0;
int minimum = 100;
for(int i = 0; i < exams.length; i++){
if (exams.get(i) > maximum) {
maximum = exams.get(i);
}
if (exams.get(i) < minimum) {
minimum = exams.get(i);
}
}
return maximum - minimum;
}
public void addExamScore(int score)
{
exams.add(score);
numExamsTaken++;
}
}
You can look more into List and ArrayList documentation at the java API website. Also, your logic for getting the minimum element is not correct, since if you have no scores that are less than 0, it will always assume that the minimum score is 0. You can fix this by setting the initial value to 100(the maximum possible value of a test score), or using another method that you prefer.
hello in the code below I am sorting (sort method) a small array to find the largest number. I then print the answer in the (display method).
But to extend my knowledge I want to mass the max value back to them main in a return statement and then print from there....simply to learn how to return a value.
package christmas;
public class maxvalue
{
public static void main(String[] args)
{
int[] data={10,90,30};
sort(data);
System.out.println("\nmax number is :");
display(data);
System.out.println(data);
}
static int display(int num[])
{
System.out.print(num[0] + " ");
return num[0];
}
static void sort(int num[])
{
int i, j, temp;
for(i=0; i<num.length-i;i++)
{
for(j=0; j<num.length-i-1;j++)
{
if(num[j]<num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
}
}
the output is:
max number is :
90 [I#4617c264
90 is the max value as printed by the display value. But after this I have a return of the max value and then I try and print the return. But instead of an integer it looks like a memory location is being printed.
Any ideas please - I am student but this is not homework - simply trying to catch up. I appreciate that there are more elegant ways to calculate the max value in an array but what I am trying to learn is the passing of arguments to and from a method.
The reason is that you are trying in your last System.out to print data, which is an array, and that's the reason why you see a memory address.Try printing display(data) and you will see as the output the desired number.
try System.out.println(data[0]);
data is your array therefore printing data without an index will only print its memory location
Instead of printing the returned value, you are printing the data array memory location:
System.out.println(data);
You should change that line with:
System.out.println(display(data));
With that line we have:
Your display method is called and it prints the max value
Your display method returns the max value
println takes that returned value and prints it
private static int sort(int[] array){
int a, b, max = 0;
for (int i = 1;//If i was 0, it would have thrown an ArrayIndexOutOfBoundsException.
i < array.length; i++){
a = array[i-1];//The first element in the array.
b = array[i];//The second one, and so on.
if (a > b) max = a;//Check the bigger number.
else max = b;
}
return max;
}
private static void display(int nr){
System.out.print(nr);//Or what you want to do with the number.
}
public static void main(String[] args){
int[] data={10,90,30};
display(sort(data));
//Or do it like this.
int max = sort(data);
display(max);
}
How do u write to a next array index by modifying this code? I'm a noob at java. for e.g, I am calling this method from my main method, so the first time it is run, it writes to index 1 of the array. the second time it is run, it writes to index 2 of the array. however, I do not want it to loop. I have also not learnt arraylists' yet so its out of the picture unfortunately.
public class staffName {
public static void staffDetails(){
String[] staffname= new String[20];
int i=0;
staffname[i]=JOptionPane.showInputDialog(null,"Please enter staff name:")
i++;
}
You are setting variable i everytime you call a function to 0. So you only change element 0 all the time. You need to put variable i outside a function and make it static so it increments when you call the function and stays incremented.
You also must put array staffname outside, otherwise, you make new empty array everytime you call a function.
public class staffName {
public static int i = 0;
public static String[] staffname= new String[20];
public static void staffDetails(){
staffname[i] = JOptionPane.showInputDialog(null,"Please enter staff name:");
i++;
}
Define the Array only once in the main and do it like this:
public class staffName {
private static int i = 0;
String[] staffname= new String[20];
public static void staffDetails(String[] array){
array[i] = JOptionPane.showInputDialog(null,"Please enter staff name:")
i++;
}
}
calling this method from my main method, so the first time it is run, it writes to index 1 of the array. the second time it is run, it writes to index 2 of the array.
Problem is both array and index loses its scope once the method staffDetails() does its job.
Option 1: Consider sending array and index as parameter
public static void staffDetails(final String[]staffname, final int i){
staffname[i] = JOptionPane.showInputDialog(null,"Please enter staff name:");
}
public static void main(String[]args){
final String[]staffname=new String[20];
int i = 0;
staffDetails(staffname,i++);
staffDetails(staffname,i++);
}
Option 2: Make array and index as class/static members
public static void staffDetails(){
staffname[i++] = JOptionPane.showInputDialog(null,"Please enter staff name:");
}
public static void main(String[]args){
staffDetails();
staffDetails();
}
private static final String[]staffname=new String[20];
private static int i = 0;
This is my first time doing Java as a part of college assignment where I have to implement Stack data structure, but the challenge is to make the code work for pushes greater than the initial array size. I am not allowed to work with ArrayList in this assignment. I can only use static array and resize when needed by copying contents to a new array and reassigning the old array as new array.
I try to achieve this using if condition which determines if the counter (which initially is 0, increases as the number of push increases) is greater than the initially defined size of the array.
Then I created a new method called stackextender where I put exceeding values in a new array called extensionstack. Then on a method mystackmodifier, I create a temparray and put contents of original stack and extensionstack in the temparray. At last i do mystack = temparray to copy the contents to my original stack. I think the code is having problem in this function (mystackmodifier),where I am modifying the contents of initial stack. The code is posted below:
public class StackOperations{
int mystack[];
int global_size;
int counter = 0;
int newcounter = 0;
int extensionstack[] = new int[counter*2];
public StackOperations(int size){
this.mystack = new int[size]; //create a stack of size as mentioned while creating object
this.global_size = size; //update the global variable
}
//the below method will allow us to calculate the number of
public void push(int value){
if (counter<global_size){
mystack[counter] = value;
counter += 1;//we have to do this unless counter < stacksize
}
else{
/*so if I have to make my code work for user input greater than my initial stack size,
I am creating a new method called stackextender where I put new value in a new array called
extension stack. Then on the method, mystackmodifier I create a temparray and put contents of
original stack and extensionstack in the temparray. At last i do mystack = temparray to
copy the contents to my original stack*/
stackextender(value);
counter ++;
}
}
//This method puts exceeding values to a new stack called extension stack
public void stackextender(int value){
extensionstack[newcounter] = value;
newcounter ++;
}
//This method modifies the contents of original stack
public void mystackmodifier(){
int temparray[] = new int[(global_size+newcounter)*2];
if(extensionstack.length>0){
int key;
for ( key = 0; key<mystack.length; key++){
temparray[key] = mystack[key];
}
for (int i = 0; i<newcounter; i++){
temparray[key+i] = extensionstack[i];
}
mystack = temparray;
}
}
Below is my main method
import java.util.*;
public class ArrayStack{
public static void main(String args[]){
StackOperations mystack = new StackOperations(100);
System.out.println(mystack.toString());
/*Although the stack size is instantiated as 10, the code works for insertion for as many
number of items as demonstrated below*/
for (int i = 0; i<150; i+=1){
mystack.push(i);
}
int stacksize = mystack.getSize();
if (stacksize == 0) {
try{
throw new NoSuchElementException();
}catch (NoSuchElementException exc){
exc.printStackTrace();
}
}
System.out.println(mystack.toString());
}
Any help will be highly appereciated
I have a problem with this code.
the function setListSize is used to set the size of an array via user input as long as it's in the range of [1-50].
The code in the function works when not in a function but when I put the code inside the function I keep getting asked to initialize listA.
Tried to do
int [] listA = null;
but then I got Null Pointer Exception error.
int [] listA;
setListSize(listA);
public static void setListSize (int [] list) {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
list = new int [listSize];
break;
}
}
}
What can I do to make this work please?
Thank you for reading
You don't want to pass in the Array (note that it is an Array not a List, they are different things):
public void setListSize () {
You want to set up your member array:
listA = new int [listSize];
Before you were passing an array into the function then overwriting the reference to that array local to the function only. What you need to do is modify the reference to the array in the main object, for which either listA needs to be static (so the static method can access it) or setListSize needs to be non-static.
To make this function generic do this:
public static int[] createList() {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
return new int [listSize];
}
}
}
Then in your calling function just do:
listA = createList();
listB = createList();
etc.
You need to make the array static, and NOT pass it in to the function. Passing it in does indeed create the array, but it only exists during the lifetime of the function. This works:
import java.util.Scanner;
public class SetListSize {
private static int [] listA;
public static final void main(String[] igno_red) {
SetListSize.setListSize();
for(int i : listA) {
System.out.println(i);
}
}
public static void setListSize () {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
//Reference the array statically
SetListSize.listA = new int [listSize];
break;
}
}
}
}
Output:
[C:\]java SetListSize
Enter array size for between [1-50]: 12
0
0
0
0
0
0
0
0
0
0
0
0
public static int[] setListSize () {
...
return new int[listSize];
The problem is that passing a variable to a function will not be able to assign to that variable; in fact you are passing the value null. And have in the function a local variable list initialized with null.
You should understand what Java does inside.
When you have a method(int[] array)
And you assign something to the variable: array = new int[size], Java creates a new array and points the variable 'array' to the new array.
So if you want to assign a value a field outside the method, you should just do it. Call listA directly and assign a value to it.