ArrayList rangecheck error - java

I'm trying to refer to an arraylist I've initiated in a method, but when I try to remove something from that ArrayList, I get an error saying that the size of my ArrayList is 0. However, after I set the values of the ArrayList, it prints out the size of the ArrayList, which I have called 'school'. Here is my code.
import java.util.*;
public class SchoolSolver{
public static ArrayList<Girl> school = new ArrayList<Girl>();
public static ArrayList<Girl> used = new ArrayList<Girl>();
public static void main(String[] args){
resetSchool();
//System.out.println(school.size());
boolean notPossible = false;
for(int i = 0; i < 7; i++){
if(notPossible){
resetSchool();
} else {
newDay();
}
for(int j = 0; j < 5; i++){
//randomGirl() is where my error happens
Girl leader = randomGirl();
used.add(leader);
}
}
}
/*Below are the two methods where I suspect the error may originate from */
public static void resetSchool(){
school.clear();
for(int i = 0; i < 15; i++){
//System.out.println("ran");
school.add(new Girl(i));
}
for(Girl g : school){
ArrayList<Girl> classmates = new ArrayList<Girl>();
for(int i = 0; i < 15; i++){
if(i!= g.getID()){
classmates.add(new Girl(i));
}
}
g.setClassmates(classmates);
}
}
public static Girl randomGirl(){
return school.remove(0);
}
Thanks and I appreciate the help!

You have a never ending loop
for(int j = 0; j < 5; i++)
See how you increment i instead of j. This means you keep on calling randomGirl, which removes a Girl from the list each time it is called. So after a while (15 times) your list becomes empty, and you still call randomGirl, which results in the exception

Related

Why are my arrays returned blank from a method but the code works fine when running in the main-Method?

I'm having following problem with my program.
It's a "connect four" Java console application.
When starting my program, I reset 3 things.
A multi-dimensional char array
public final int rows = 8, columns = 8;
public char[][] board = new char[rows][columns];
I reset it with a for-loop, overwriting every array field with the character '.', which is my default board texture.
public char[][] resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
return board;
}
An integer-array
public int[] nums = new int[columns];
I reset it with a for-loop using the variable i, since I just need an array with the length of columns, which just counts up from 1. It is used so the user know which column he's choosing. Like in chess "A6" e.g., except without letters.
public int[] resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
return nums;
}
An integer
public int roundCounter = 0;
The integers keeps track of how many rounds there have been in the current game. I want it to be printed while playing.
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return roundCounter = 0;
}
I reset these looking like this:
gameMain main = new gameMain();
gameMode mode = new gameMode();
gameCheck check = new gameCheck();
main.board = main.resetBoard();
main.nums = main.resetNums();
check.roundCounter = check.resetRoundCounter();
My problem is when printing the game board, the nums-array and the round counter none seem to work.
The game board is just completely blank. The nums-array is only 0's and the round counter stays at 0.
When running the code in the main-method it worked better than running it through classes etc.
My print method:
public void printBoard() {
gameMain main = new gameMain();
gameCheck check = new gameCheck();
// Printing number array with space in between the elements
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
// Printing the round count next to the number array
System.out.println(" Round " + check.getRoundCounter());
for (int i = 0; i < main.rows; i++) {
for (int j = 0; j < main.columns; j++) {
System.out.print(main.board[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
System.out.println("\n");
}
I could really use some help, since I've been up all night. Originally due to how much fun I was having programming this, now it has become frustrating.
Thanks for reading and thanks in advance!
I think what is happening to you is related to the references of the objects you are using. You are mixing two different ways of working, I give you an example:
You can use the reference of 'roundCounter' and work on it:
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
or you can return it, like this:
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return 0;
}
In the first case, you will have to call the function like this:
resetRoundCounter(); //this function changes the value of your variable.
In the second case, you will have to call the function like this:
roundCounter = resetRoundCounter();
You can choose the way you like to work but I recomend you not working with global variables especially working with methods. I hope it helps you.
Do it as
public void resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
}
public void resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
}
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
Finally, call them as follows:
gameMain main = new gameMain();
gameCheck check = new gameCheck();
main.resetBoard();
main.resetNums();
check.resetRoundCounter();
I also recommend you follow Java Naming Convention e.g. gameMain should be GameMain and gameCheck should be GameCheck.

Issue trying to create a Bubble Sort using ArrayList<Integer>

Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}

How to search for a keyword in an array of objects and copy that object to another array

I'm working on a school assignment and i ran into some trouble. Basically I have an array of objects with a String name attribute, I want to search through that array with a keyword, and pick out any of the objects with that word and store it into another array. I can only use an array, and not arraylist or treemaps, etc. I get a problem where it only gets one of the objects and not the others, the keyword is "is".
this what I have so far:
import java.util.Arrays;
public class TesterTwo
{
public static void main(String[] args)
{
TestObj t1 = new TestObj("Where is my house",1);
TestObj t2 = new TestObj("Canada is really cold",2);
TestObj t3 = new TestObj("It's a big world",3);
TestObj t4 = new TestObj("What is This",4);
TestObj t5 = new TestObj("I'm at home",5);
TestObj[] thingy = new TestObj[]{t1,t2,t3,t4,t5};
System.out.println("BEFORE");
for(int a = 0; a < thingy.length; a++)
{
System.out.println(thingy[a].getName());
}
TestObj [] searchResult = new TestObj[5];
for (int i = 0; i < thingy.length; i++)
{
if(thingy[i].getName().contains("is"))
{
int j = 0;
searchResult[j] = thingy[i];
j++;
}else{continue;}
}
thingy = searchResult;
System.out.println("After the search has gone through:");
System.out.println("");
for(int i = 0; i < thingy.length; i++){
if(thingy[i] == null){break;}
System.out.println(thingy[i].getName());
}
}
}
EDIT:
I found out i was doing the loop wrong my bad.
Here's my fix:
TestObj [] searchResult = new TestObj[thingy.length];
for (int i = 0, k=0; i < thingy.length; i++)
{
if(!thingy[i].getName().contains("is"))
{
continue;
}
searchResult[k++] = thingy[i];
}
thingy = searchResult;
The problem is in the scope of declared j integer variable.
Now you have it declared inside of the for loop which makes the scope of j available only for a single iteration. At the end of iteration the j variable is removed and new iteration makes new one.
Move the declaration of j outside of the for loop:
int j =0;
for (int i = 0; i < thingy.length; i++)
{
if(thingy[i].getName().contains("is"))
{
//...
}
}
Additionaly the whole else statement is not needed because the if statement is kinda last in the loop and if the if is false the loop will try to go to the next iteration.
Edit:
The fix you provided has a bit of performance improvement than my original answer. Using second variable in the for statement makes it avaiable through all iterations and after the loop is finished the variable will be removed from memory, so to the sample I provide it would be:
for (int i = 0, j =0; i < thingy.length; i++) { //...

JAVA Need help involving matrices and arrays

I'm working on a test prep program. Its not homework or for a grade, I just need help finishing and fixing it so I can study and better understand how it works. The directions are "Write a program named Matrix1.java that randonly fills in 0s and 1s into an n-by-n matrix, prints the matrix." I'm still pretty new to coding so any help would be greatly appreciated. This is the code I have so far:
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix=new Matrix1(5);
matrix.fill();
matrix.print();
}
public Matrix1(int n){
int[][] matrix = new int[n][n];
}
public void fill(int n){ // randomly fill in 0s and 1s
Random rand = new Random();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
Integer r = rand.nextInt;
matrix[i][j] = Math.abs(r);
}
}
}
public void print(int[][]matrix, int n){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.println(array[i][j]);
}
}
}
}
I ended up confusing myself and I'm not sure how to fix it or continue. I think I'm partially on the right track though.
Your code after fixes.
import java.util.Random;
public class Matrix1 {
private final int[][] matrix;
private final int n;
public Matrix1(int n) {
this.n = n;
this.matrix = new int[n][n];
}
/**
* randomly fill in 0s and 1s
*/
public void fill() {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = rand.nextInt(2);
}
}
}
/**
* print the matrix, each row is printed in a separate line
*/
public void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
}
So changes I've made:
I've changed "matrix" and "n" variables into class fields, so you don't have to pass them through class methods
filling array - it should be just 0/1 not any integer so you can use rand.nextInt(2) with bounds - it gives values less then 2
printing array - you have to print row in one line, then change line
It looks like the right direction, check your main method to set the necessary parameters (size, array and size).
Also set the Random object to only be 0 or 1 (Check the Java class libraries for the answer) I believe you can set a parameter inside the Random.nextInt method.
Also if its required to print it like a double array, change up your printing logic since you are always writing to a new line
Well, I see a few problems, which if fixed might help get you on the right track.
First of all, for the random integer, you'll probably want to use the method from this answer:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);
I don't think you need to use Math.abs in this case, as long as you call ThreadLocalRandom.current().nextInt(0, 2).
Second, there are a couple of problems with your printing code. First of all, you should be using matrix[i][j] instead of array[i][j]. Second, you'll want to use System.out.print instead of System.out.println.
It should be something like this:
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.print(matrix[i][j]);
}
System.out.println();
}
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
private int[][] m; //it is easier use a global variable
public Matrix1(int n){
m = new int[n][n];
}
public void fill(){ // randomly fill in 0s and 1s
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m.length; j++){
if (Math.random() > 0.5) {
m[i][j] = 1;
} else {
m[i][j] = 0;
}
}
}
}
public void print(){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< m.length; i++){
for(int j = 0; j<m.length; j++){
System.out.print(m[i][j]); //only use print() for the same row
}
System.out.println("");
}
}
}

Having trouble calling an array from one method to another in Java

The way I have my code set up is I declare my array in one method then I want to print it out in a table like fashion in another. But I want to do this while only using the main() function.
I have taken most of the irrelevant code out so here is my code:
public static void main(String[] array) {
test2(array);
}
public static void test() {
String[] array = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
When I try and run it, it comes up with the java.lang.ArrayOutOfBound on the line "System.out.print(array[count] + "\t");"
Does anyone know why this is and/or how to fix it?
You have several errors:
You create array as a local variable in test().
You use the arguments of the application as parameters.
You don't even call test().
The consequences are that you call your application probably with no parameters and end up having the test2() method trying to access the first element of an empty array, causing your exception.
This is what you should do, but keep reading after the code, I'm not done:
public static void main(String[] args) { // This array is defined, but don't use it.
test2(test());
}
public static String[] test() {
return new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
This code has still issues. You indeed assume that you have 16 elements in your array. Yet you're not sure. Oh yes, you're sure because you've added them, but you shouldn't assume that it'll always be the case.
Therefore it's nice to check for the actual number of the elements anyways.
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (count < array.length) {
System.out.print(array[count] + "\t");
count++;
}
}
System.out.println();
System.out.println();
System.out.println();
}
}
Well, it doesn't work because when your "main" calls "test2(array)" it passes nothing, since main doesn't have an "array" defined in it.
The array that you want exists only inside the "test" method.
So, one simple solution would be to change your code to:
public static void main(String[] array) {
test2(test());
}
public static String[] test() {
String[] array = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
return array;
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
...so that the method test() returns the array when it's called in main.
But, still, the code doesn't make lots of sense, especially in Object Oriented programming.

Categories

Resources