This question already has answers here:
Variable might not have been initialized error
(12 answers)
Initializing multiple variables to the same value in Java
(7 answers)
Closed 5 years ago.
I am trying to assign 3 integer arrays to a method that returns one version. But when i try this it says variable bubbleArray and variable insertionArray have not been initialized. Is there another way to do this and still keep the same original values from the method.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
bubbleSort(radioValue,bubbleArray);
selectionSort(radioValue,selectionArray);
insertionSort(radioValue,insertionArray);
public Integer[] numGenerator() {
Random rn = new Random();
originalOutput.setText("");
sortedOutput.setText("");
referenceArray.clear();
if (number10Button.isSelected()) {
for (int i = 0; i < 10; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number100Button.isSelected()) {
for (int i = 0; i < 100; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number1000Button.isSelected()) {
for (int i = 0; i < 1000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number5000Button.isSelected()) {
for (int i = 0; i < 5000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
}
Integer[] bubbleArray = referenceArray.toArray(new Integer[referenceArray.size()]);
return bubbleArray;
}
Your code declares 3 Integer[] variables and assigns the last one to what numGenerator() returns.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
Now since you want three arrays, not just three variables pointing to one array you need to make copies of the array, for example with clone(). If you don't make copies you will have one array which is sorted by bubble sort and the other sorting methods will try to sort an already sorted array, which is not what you want.
Integer[] bubbleArray = numGenerator();
Integer[] insertionArray = bubbleArray.clone();
Integer[] selectionArray = bubbleArray.clone();
Related
This question already has answers here:
Getting minimum time difference
(4 answers)
Closed 2 years ago.
I have four different timestamps where I have to find the smallest difference in minutes. I'm confused on how to do this.
Example:
String array: ["2:10pm", "1:30pm", "10:30am", "4.42pm"]
How can I find the smallest difference in minutes. Do I use LocalDate?
This will help you to get smallest in minutes from array
public class Main
{
public static void main(String[] args) {
String[] myarr = {"2:10pm", "1:20pm", "10:30am", "4:42pm"};
int index = 0;
int smallest = Integer.parseInt(myarr[0].substring(myarr[0].lastIndexOf(":") + 1,myarr[0].lastIndexOf(":") + 3));
for (int i = 1; i < myarr.length; i++){
int myValue = Integer.parseInt(myarr[i].substring(myarr[i].lastIndexOf(":") + 1,myarr[i].lastIndexOf(":") + 3));
if (myValue < smallest){
smallest = myValue;
index = i;
}
}
System.out.println(myarr[index] + " is smallest in minutes");
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
import java.util.Scanner;
public class Java3{
int sumAll = 0;
int sumFive = 0;
int sumLast = 0;
int arr[];
int n;
void arraySum(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
sumAll += arr[i];
if (i == 4)
sumFive += sumAll;
if (i >= (arr.length - 5))
sumLast += arr[i];
}
System.out.println("sum all = " + sumAll
+ " sum first five " + sumFive
+ " sum last five " + sumLast);
}
public static void main(String [] args) {
Java3 obj1 = new Java3();
Scanner scan1 = new Scanner(System.in);
System.out.println("enter the number of elements");
obj1.n = scan1.nextInt();
System.out.println("enter the elements");
for (int i = 0; i < obj1.n; ++i)
obj1.arr[i] = scan1.nextInt();
obj1.arraySum(obj1.arr);
}
}
The error I get
java.lang.NullPointerException
Errors on Null pointer exception has been asked and answered several times before, but I do not understand those explanations. Can anyone please explain it in a very easy manner. This is my code, and it is showing me the error at runtime.
This code is supposed accepts the size of an integer array followed by the integer array. Then calls a function which calculates:
sum of all digits
sum of first 5 digits
sum of last 5 digits
and prints each value in the console..
Seems like you are a beginner in coding, nullPointerException occurs whenever you are trying to access the value of an object that is not defined.
In your case you did not define your array. You should have defined your array as given below before trying to add values into the array this will remove the exception.
obj1.arr = new int[obj1.n];
Doing this will define your array in your object and with obj1.n it will initialize its size. Hope you can proceed from here. Please refer the usage of new and constructors in java.
The problem was you took the length of array as input , but you did not initialize the array . Please add this one line in the code:
obj1.n = scan1.nextInt();
obj1.arr = new int[obj1.n];
You should define your arr size. until you define the arr size it is null, and there is no memory will be allocated. You can avoid this by using ArrayList instead of array or define your arr with sum big number of size and asker user to enter the number of values less than that size.
int arr[] = new int[100];
define the array size once you know the value
obj1.arr = new int[obj1.n+1];
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
Recently I've been slamming by head against this piece of code:
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
SqrTileNormal temp = new SqrTileNormal(i, j, this, ID.Tile);
setTile(temp);
}
}
//additional info
public void setTile(Tile tile) {
int xPosGrid = tile.getXPosGrid();
int yPosGrid = tile.getYPosGrid();
System.out.println("Coords: (" + xPosGrid + ", " + yPosGrid + ")");
this.tiles.get(xPosGrid).set(yPosGrid, tile);
}
//how the nested array looks like.
protected List<ArrayList<Tile>> tiles;
It's part of a constructor which is supposed to fill a two-dimensional array with SqrTileNormal. I have found what the issue is: Every iteration of the for loop keeps rewriting the previous iterations, so they all end up whit the same xPosGrid and you see this:
I have been trying some things but I usually keep the overwriting issue and I don't want to make it unnecessarily complicated and long. Does anyone know of a solution to this problem? Any help would be appreciated!
Edit:
What I had:
[[null, null, null...][null, null, null...][(null, null, null...]
What I want:
What I get:
[[(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)]...]
The problem is in how you initialize this.tiles, you are not showing how you do it but possibly you are setting just 1 array list, so in fact you have ten times the same value list.
Your this.tiles init should look like:
private static List<List<Tile>> getListOfLists() {
int numcol = 5;
int numrow = 5;
List<List<Tile>> bidiArray = new ArrayList<>();
for (int i = 0; i < numcol; i++) {
List<String> sublist = new ArrayList<>();
bidiArray.add(sublist);
for (int j = 0; j < numrow; j++) {
sublist.add(null);
}
}
return bidiArray;
}
But in fact, dealing with a fixed number of columns and rows I would rather use arrays such as :
Tile[][] bidiArray = new Tile[numcol][numrow];
And then set it like this:
this.tiles[xPosGrid][yPosGrid]= tile;
This question already has answers here:
How to count the number of occurrences of an element in a List
(25 answers)
Closed 6 years ago.
I'm trying to do a Blackjack game but I don't know how to change the value of "ACE" to 1 if 11 is too high. I'm now trying to search a Arraylist for A's to change the value of one ore more of them. But how can I see how much A's are in my Arraylist?
while (getPointsPC() < 17 || getPointsPC() < getPointsPL()){
int acees = 0;
random = bj.getRandom();
CardsPC.add(bj.getCard(random));
setPointsPC(random);
lblPointsPC.setText("Points Dealer: " + Integer.toString(getPointsPC()));
String text = CardsPC.get(0);
for(int i = 1; i < CardsPC.size(); i++){
text = text + ", " + CardsPC.get(i);
}
if (CardsPC.contains("A") && getPointsPC() > 21 && acees < CardsPC.**HOW_MUCH_A's???**){
setPointsPC(13);
acees++;
}
lblCardsPC.setText(text);
}
Is your CardsPC is your mentioned ArrayList? Just set counter variable:
String text = "";
int counter = 0;
for(int i = 0; i < CardsPC.size(); i++){
text = text + (i > 0 ? ", " : "") + CardsPC.get(i);
if (CardsPC.get(i).contains("A")) { // or use equals, base on your input.
counter++;
// do something with found "A" element if you want.
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
I'm trying to create a program that removes a given character from an array and then prints out the new array and whenever I print it out I get weird results like [I#120acab
public static int[] removeVal(int[] numArray, int val)
{
int purge = 0;
int keep = 1;
int arrayVal = 0;
for (int item : numArray)
{
if(item == val)
purge = purge + 1;
else
keep = keep + 1;
}
int[] newArray = new int[keep];
for (int taco : numArray)
{
if(taco != val)
newArray[arrayVal] = taco;
arrayVal = arrayVal + 1;
}
return newArray;
}
You should use Arrays.toString to print the array. This will show the individual elements of the array.
The default toString implementation of Object class returns what you see.