Compare element of int array to an int - java

Hi I'm seeking to understand in java how you can take an int array and then in an if statement compare one single element from the int array against just a declared int. I want to just simply compare two ints against each other but one is inside of an int array. The == I guess doesn't work?
for (int count = 5; count >= 0; count--) {
if (gameBoardTokens[count] == 0) {
if (playerOneTurn) {
gameBoardTokens[count] = 1;
count = 0;
} else {
gameBoardTokens[count] = 2;
count = 0;
}
}
}

you need to change this (count < -1) for this (count > -1)
because at first 5 > -1 not -1 > 5.

gameBoardTokens[count] == 0 works. The thing that makes your code unfunctional is that the code in the for-loop is never executed, because count is initially 5, for which count < -1 is false. So the loop immediately aborts.

Related

How to add an element in a null array in java?

I have created a function that takes an array and outputs another array. So I have declared the result array (which will be the output) as null cause the size varies and depends on the inputted array. (for eg. if I enter an array of integers and then I want to output the array containing even numbers from that array). So I will be using for or while loops and I want to know that how I can add the integer to that null array. I tried but I get a null pointer exception that says cannot store to int array cause "array" is null.
sorry but I can't use more advanced techniques cause I am new to java (I need to make this without using arraylist library as I am learning coding I found those type of questions which tries to make you perfect in i specific topic and then they take you to next step so u can be more prepared)
I am using this code and I want to know that add an element to my result array or should I initialized it as null or something else cause the size depends on inputted array in this code I am getting null pointer exception
public static int[] even(int[] numbers) {
int[] result = null;
int even = 0;
int i = 0;
int a = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
even = numbers[i];
result[a] = even;
a++;
}
i++;
}
return result;
}
The array's size needs to be initialized. If you want dynamic storage , read about List and Collection.
Here, if you still want to use array, you need the count.
int a = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
a++;
}
i++;
}
Then after this, you can initialize it as int[] result = new int[a];
public static int[] even(int[] numbers) {
int[] result = null;
int j = 0;
int a = 0;
while (i < numbers.length) {
if (numbers[j] % 2 == 0) {
a++;
}
j++;
}
result = new int[a];
int even = 0;
int i = 0;
int b = 0;
while (i < numbers.length) {
if (numbers[i] % 2 == 0) {
even = numbers[i];
result[b] = even;
b++;
}
i++;
}
return result;
}

String indexOf method is not working for first character in the String

I am implementing a code for counting number of occurrences for all the characters in a String. I have used indexOf() method to check occurrences. But it's not working for the first character.
The following code works fine for all characters except the first character.
public static void main(String[] args) {
String str = "simultaneously";
int[] count = new int[str.length()]; //counter array
for (int i = 0; i < count.length; i++) { //initializing counters
count[i] = 0;
}
for (int i = 0; i < str.length(); i++) {
int index = -1;
char c = str.charAt(i);
while (1 > 0) {
if (str.indexOf(c,index) > 0) { //This is not working for
//the first characters
index = str.indexOf(c, index) + 1;
count[i]++;
} else {
break;
}
}
}
for (int i = 0; i < count.length; i++) {
System.out.println(str.charAt(i) + " occurs " + count[i] + " times");
}
}
Index for arrays in java starts from 0.
Change the condition from
if (str.indexOf(c,index) > 0) {
to
if (str.indexOf(c,index) >= 0) {
And also, the for-loop to initialize the counter is redundant, by default, all the values in the int array is initialized to 0.
str.indexOf(c,index) would return 0 for the first character, but your condition checks whether str.indexOf(c,index) > 0. Change it to str.indexOf(c,index) >= 0.
There is some thing else you need to know
str.indexOf(c,index)
will search for the character c from the index 'index' which is -1 in your case for the first character that is it will never find this because starting point of string is 0
also change your condition as following
str.indexOf(c,index) >= 0
The index of arrays and Strings (which are array of characters) always start at 0 in Java.
You also want to check position 0, so include >=.
if (str.indexOf(c,index) >= 0) {
Also, using breaks can sometimes be confusing.
In your code, your while-loop is an infinite True and then you break out of it when necessary.
Take a look at this code below. It serves the same purpose that you want to accomplish.
It is much cleaner and clearer as it removes the break from the whileloop and you simply check to see if the statement is True at the beginning of the while-loop rather than inside it.
for (int i = 0; i < str.length(); i++) {
int index = 0;
char c = str.charAt(i);
while (str.indexOf(c,index) >= 0) {
index = str.indexOf(c, index) + 1;
count[i]++;
}
}

Confused about java assignment method

Hi guys so right now I'm taking data structures in school and I'm having trouble understanding the code our homework is based on which was created by the teacher.
Basically its a program designed to store integers and assign them sets depending on if their positive, negative, and a set that keeps track of weather or not the last entry of an integer was either. We have a class that creates a new array with the storage of whatever int is passed to it. We also have a insert method that inserts an int into a collection only if its not already there. heres the code:
public IntColl1(int i){
c = new int[i+1];
c[0] = 0;
}
public void insert(int i){
if (i > 0){
int j = 0;
while ((c[j] != 0) && (c[j] != i)) j++;
if (c[j] == 0){
if (j == c.length - 1){
int newLength = (c.length * 2);
int[] d = new int[newLength];
for(int l = 0; l < c.length; l++){
d[l] = c[l];
}
c = d;
}
c[j] = i;
c[j + 1] = 0;
}
}
}
Its supposed to insert the Int into the array and if the array is too small, it creates a new one with double the length. For test we set Intcoll1(1), Can anyone help by explaining the while loop that is inside the first if statement? I always thought that when an empty array is created that the slots were all set to 0, and if thats the case then wouldn't that while loop always be false?
It appears that the while loop is trying to find the next "available" space in the array. Initially (as you correctly stated) the while condition will immediately be false. After a couple of inserts, it will be more useful.
Assuming an initial array size of 5, c would start out looking like
[0,0,0,0,0]
If I call insert(4), the condition
(c[j] != 0) && (c[j] != i)
Fails, so j is never incremented and 4 is inserted as position 0. Now c looks like
[4,0,0,0,0]
Now if I call insert(7), the condition will be initially satisfied when j is 0, but will fail when j is incremented to one, so 7 will be inserted as position 1:
[4,7,0,0,0]
Can anyone help by explaining the while loop that is inside the first if statement?
Well I feel that there is a problem in understanding your program above. So I am re-writing the code to make it clear to your:
public void insert(int i){
if (i > 0){
int j = 0;
while ((c[j] != 0) && (c[j] != i)){ //Introduced this bracket to show the start of while
j++;
} //Introduced this bracket to show the end of while
if (c[j] == 0){
if (j == c.length - 1){
int newLength = (c.length * 2);
int[] d = new int[newLength];
for(int l = 0; l < c.length; l++){
d[l] = c[l];
}
c = d;
}
c[j] = i;
c[j + 1] = 0;
}
}
}
The next if statement if (c[j] == 0) is not inside the while loop. Hope that now your understand it.

counting number of unique elements

Hi so I am supposed to count the number of unique elements after an array sort excluding duplicates but i'm getting the wrong output.
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
Arrays.sort(whitelist);
int count = 0;
for (int i = 0; i < whitelist.length; i++) {
if (whitelist[i] == whitelist[count]) {
count++;
}
}
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
rank(key, whitelist);
}
System.out.println(count);
}
}
expected output: java InstrumentedBinarySearch tinyW.txt < tinyT.txt
65
got: 16
Did i count the number of duplicates or something?
int flag = 0;
int count = 0;
for (int i = 0; i < whitelist.length; i++) //Element to be checked for
{
for (int j=0; j< whitelist.length ; j++) //Loop that goes through the whole array
{
if (whitelist[i] == whitelist[j]) //checks if there are duplicates
{
flag++; // count
}
}
if( flag==1) //There should be only 1 instance of the element in the array and that is the element itself
{
System.out.println(whitelist[i]); //displays unique element
count++; // Keeps count
}
}
This algorithm counts how many different unique numbers there are in the array. A number appearing more than once will only count for 1. I am assuming this is what you mean, as opposed to "numbers which appear exactly once".
There is a more trivial way to do it, as proposed in another answer, but it requires a nested for-loop and therefore executes in quadratic complexity. My algorithm below attempts to solve the problem in linear time proportional to the array size.
int uniquesFound = 0;
// Assume that array is sorted, so duplicates would be next to another.
// If we find duplicates, such as 12223, we will only count its last instance (i.e. the last '2')
for (int i = 0; i < whitelist.length; i++) {
// If we are at the last element, we know we can count it
if (i != whitelist.length - 1) {
if (whitelist[i] != whitelist[i+1]) {
uniquesFound++;
}
else {
// Nothing! If they are the same, move to the next step element
}
} else {
uniquesFound++;
}
}
For instance, given the array:
{1,2,3} this will yield 3 because there are 3 unique numbers
{1,2,3,3,3,4,4,4,5} this will yield 5 because there are still 5 unique numbers
First let's take a look at your loop:
for (int i = 0; i < whitelist.length; i++) {
if (whitelist[i] == whitelist[count]) {
count++;
}
}
You should be comparing consecutive elements in the list, like whitelist[0] == whitelist[1]?, whitelist[1] == whitelist[2]?, whitelist[3] == whitelist[4]?, etc. Doing whitelist[i] == whitelist[count] makes no sense in this context.
Now you have two options:
a. Increment your counter when you find two consecutive elements that are equal and subtract the result from the total size of the array:
for (int i = 0; i < whitelist.length - 1; i++) {
if (whitelist[i] == whitelist[i + 1]) {
count++;
}
}
int result = whitelist.length - count;
b. Change the condition to count the transitions between consecutive elements that are not equal. Since you are counting the number of transitions, you need to add 1 to count in the end to get the number of unique elements in the array:
for (int i = 0; i < whitelist.length - 1; i++) {
if (whitelist[i] != whitelist[i + 1]) {
count++;
}
}
int result = count + 1;
Note that, in both cases, we loop only until whitelist.length - 1, so that whitelist[i + 1] does not go out of bounds.

Magic Square Java program

//Kevin Clement
//Week3A Magic Squares
Hey all, doing an introductory assignment to 2dimensional arrays. Below is the code I have done which is pretty much done.
My problem I get is I'm not entirely sure how to print out the array, as well as getting everything to run right with a test method. I get an error out of bounds at the line msq[order][order] = 1;
I apologize if my formatting of question is wrong, still not used to this site. Any help would be great. Thanks!
import java.util.*;
class Magic
{
private int order;
int msq[ ][ ];
public Magic(int size)
{
if(size < 1 || size % 2 == 0)
{
System.out.print("Order out of range");
order = 3;
}
msq = new int[order][order];
Build();
Display();
}
public void Build()
{
int row = 0;
int col =0;
msq[order][order] = 1;
for(int k = 1; k <= order * order; k++)
{
msq[row][col] = k;
if(row == 0 && col == order -1)
row++;
else if(row == 0)
{
row = order - 1;
col++;
}
else if(msq[row - 1][col + 1] != 0)
row++;
else if(msq[row -1][col + 1] == 0)
{
row--;
col++;
}
if(col == order - 1)
{
col = 0;
row--;
}
}
}
public void Display()
{
for(int i = 0; i < order; i++)
{
for(int k = 0; k < order; k++)
{
System.out.println(msq[i][k] + " ");
}
}
}
}
I get an error out of bounds at the line msq[order][order] = 1;
msq = new int[order][order];
// ..
msq[order][order] = 1;
If array size is n, then you need to access the elements from 0 to n-1. There is no nth index. In your case there is no order, order index. It is only from 0 to order-1 and is the reason for array index out of bounds exception.
What is the reason for this condition in the constructor?:
if(size < 1 || size % 2 == 0)
{
System.out.print("Order out of range");
order = 3;
}
Note that whenever you use a size input that doesn't satisfy the if clause, the variable order is not initialized and defaults to 0. As a result the 2d array has size zero and throws the out of bounds error. If you are trying to use 3 as a default value, then u want to move the line:
order = 3;
before the if block.
Other things to consider:
1. make the order variable final since u don't plan on changing it. Eclipse IDE would warn you about the situation described above if you do so.
or
2. If you are going to default to 3 for the value of order initialize it as such.
private int order = 3
Also you might consider printing a message saying order defaults to three when the condition is not satisfied.
To print a matrix of integers in Java
for (int i = 0; i < order; i++) {
for (int k = 0; k < order; k++) {
System.out.printf("%6d", msq[i][k]);
}
System.out.println();
}
The second part of your question is answered by Mahesh.
msq[order][(order] = 1;
--> here is a syntax error. You have an '('.
You get end of bound error because array start from 0 not 1 (which is a mistake every beginner makes) therefore change it to msq[order-1][order-1] = 1;
The answer above is the correct way to print out the array.

Categories

Resources