What exactly does this piece of code do? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am a beginner programmer,
I have an array called myArray and was wanting to know what exactly the if statment in this code does. Also what does myArray[count] do?
for(int i = 0; i < count; i++)
if (number == myArray[i])
{
containsNumber = true;
}
if ( !containsNumber )
{
myArray [ count ] = number;
count++;
} // end if
Cheers

Notice
Because the code is not complete I have to do some assumptions:
All variables are declared and initalized before
count represents the number of elements in the array
The array is sufficiently sized
containsNumber is initalized with false
Short
It checks if the given number exists in the array and if not it will add it.
Explained
At first, to make it a bit more readable we can add two braces after the for instruction:
for(int i = 0; i < count; i++)
{
if (number == myArray[i])
{
containsNumber = true;
}
}
if ( !containsNumber )
{
myArray [ count ] = number;
count++;
} // end if
Because there are no breaces after the for it will just affect the following statement or block, which is the if statement.
At first the code will loop through the array and check every position smaller than count (value of i ) for the given number.
If the value is found (if (number == myArray[i])) the variable containsNumber is set to true.
After iterating over the array the variable containsNumber is checked.
An if statement must contain a boolean value, so you can just write if (containsNumber) instead of if (containsNumber == true).
The ! negates the boolean value. That means you check if containsNumber is not true. if (containsNumber != true) or if (containsNumber == false) would be the same.
If the number is not in the array (containsNumber is false) than it is added at the next position (myArray [ count ] = number;) and count is incremented by one (count++;).
Example
Let's say the array contains the values 1, 5 and 7.
Number has the value 4 and count is 3 because the array contains 3 elements.
For loop:
First iteration
i has the value 0 --> 0 is smaller than 3 (count)
if (number == myArray[i]) --> if (4 == myArray[0]) --> if (4 == 1)
--> false
Second iteration
i has the value 1 --> 1 is smaller than 3 (count)
if (number == myArray[i]) --> if (4 == myArray[1]) --> if (4 == 5)
--> false
Third iteration
i has the value 2 --> 2 is smaller than 3 (count)
if (number == myArray[i]) --> if (4 == myArray[2]) --> if (4 == 7)
--> false
Fourth iteration
i has the value 3 --> 3 is not smaller than 3 (count)
for ends
Next step
containsNumber is still false
if ( !containsNumber ) --> the value of containsNumber is negated what means if (true)
myArray [ count ] = number; --> myArray [ 3 ] = 4;
The value of number (4) is set to the fourth position of the array (remember, the array starts with 0).
Now the array contains the values 1, 5, 7 and 4.

It seems to me that it's searching for a value. If it exists, skip. If it doesn't, add it in. Here's the pseudocode:
for i = 0 to the value in count
if number is equal to myArray at position i
Set a flag to say the number has been found.
if(the flag is not set, the number has not been found)
Set myArray at position count to the number i'm searching for
increase count.

if the "number" is not in the "myArray" Array the number would assign to the array on the current position (count).

The first if statement
if (number == myArray[i])
checks if the item at position i in the myArray is equal to the value that the variable number contains
The second if statement
if ( !containsNumber )
Checks if the value of the variable containsNumber is false. If it is, it probably means that the array doesn't contain the number
In this case, myArray [ count ] = number; set the item at position count of the array to the number that you were previously searching, so that now the array contains also this value

There are two if statements, which one do you mean?
if (number == myArray[i])
If number is equal to element i in myArray.
if ( !containsNumber )
If containsNumber is false.

It will check the number in myArray. If myArray didn't contain number then it will store the number at last index of myArray specified by count and increment count by 1.

The first IF statement
if (number == myArray[i])
checks if the number is there in myArray. If not then it adds the number at the current index position & increments the count.

Actually, the code that you put only checks if the value 'number' exist in the array 'myArray'. Then, an IF condition checks if the variable containsNumber and increases the limit 'count' used in the FOR. But this IF condition is not part of the FOR, it is outside.
Probably it lacks of curly brackets to delimitate the FOR.
This is what is interpreted by the machine:
for(int i = 0; i < count; i++)
if (number == myArray[i])
{
containsNumber = true;
}
if ( !containsNumber )
{
myArray [ count ] = number;
count++;
} // end if

Related

Why here I got different results?

I have next task: Given an array of ints, return true if the array contains no 1's and no 3's.
First version and it's right:
for (int i = 0; i < nums.length; i++){
if(nums[i] == 1 || nums[i] == 3)
return false;
}
return true;
but here's I got many wrong tests:
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 1 || nums[i] != 3)
return true;
}
return false;
Can you explain me reason why does it work like this? I supposed reason is something happened in second if(...)
The code should return true if there are no 1s and no 3s.
Let us take a look at your second code:
// Iterate all values
for (int i = 0; i < nums.length; i++) {
// Return true if value is not 1 OR not 3
if (nums[i] != 1 || nums[i] != 3)
return true;
}
// Return false
return false;
The key here is the condition val != 1 || val != 3 which is a tautology, i.e. it is true in all cases. Suppose a value of 5, it is not 1, so true is returned. Now suppose a value of 1, it is 1 but it is not 3, also true is returned.
You would need to substitute || by && which means and, which also better reflects your textual condition:
return true if the array contains no 1's and no 3's
However you can not directly return true if you found the first element which is not 1 and not 3. You first need to check all elements. However you can directly return false if you found the first 1 or 3. And that is exactly the first version of your code, which is correct.
Note that when negating a conditions you need to negate all quantifiers and operators too.
The first code realizes an approach using this logic:
Not (there exists one element which is 1 or 3)
¬(∃ e : e = 1 ∨ e = 3)
When now solving the negation you receive this logic:
All elements are not 1 and not 3
∀ e : e ≠ 1 ∧ e ≠ 3
So ∃ (exists) turns to ∀ (for all), = to ≠ and ∨ (or) to ∧ (and).
Why the first one works
It returns false if any item is not 1 or 3, and true if no items match
Why the second one does not work
It returns true all the time (if any item is not equal to 1 or 3, and no integer is equal to both 1 and 3), the only way to get false is to pass it an empty array.
You're implementing a short-circuit evaluation. The first version is right. In the second version, you prematurely return true when you encounter a number that isn't 1 or 3 - which is every number, since 1 is not 3 and vise versa.
For the second answer, you are using OR instead of AND. Hence whatever value you provide, it will always enter into the if condition.
Hope this helps.

What is wrong with my code/ what can I do to solve this assignment?

In this lab, you will be creating a program that merges two arrays of positive (greater than 0) integers. Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
After the two arrays have been input, your program must check to make sure the elements of each array have been entered in order. If an out of order element is found, print the message “ERROR: Array not in correct order”.
Your task is to merge the two input arrays into a new array, with all elements in order, lowest to highest. Print out each of the original arrays entered, followed by the merged array.
Please note that your program must output the arrays with exactly one space between each of the numbers.
Sample Run 1:
Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit
3
3
5
6
8
9
-1
Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit
3
4
5
6
-5
First Array:
3 3 5 6 8 9
Second Array:
3 4 5 6
Merged Array:
3 3 3 4 5 5 6 6 8 9
My code was:
import java.util.Scanner;
class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int one1=0;
int two1=0;
int a = 0;
int b = 0;
int flag = 0;
int[]one=new int[10000];
int[]two=new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
while (a==0){
int first = scan.nextInt();
if (first<=0) a++;
else{
one[one1]=first;
one1++;
}
}
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
while (b==0){
int second = scan.nextInt();
if (second<=0) b++;
else{
two[two1]=second;
two1++;
}
}
System.out.println("First Array:");
for (int i = 0 ; i < one1 ; i++){
System.out.print(one[i]+" ");
}
for (int i = 0 ; i < one.length-1 ; i++){
if (one[i]>one[i+1]) flag++;
}
System.out.println("Second Array:");
for (int i = 0 ; i < two1 ; i++){
System.out.print(two[i]+" ");
}
for (int i = 0 ; i < two.length-1 ; i++){
if (two[i]>two[i+1]) flag++;
}
int[]combo = new int[one.length+two.length];
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
if (flag>0) System.out.println("ERROR: Array not in correct order");
else{
for (int i = 0 ; i < combo.length; i++){
System.out.print(combo[i]+" ");
}
}
}
}
This code keeps giving me runtime error- what am I doing wrong?
I am sorry, your merge algortithm is all wrong. You create an array combo of length one.length + two.length, that is, 20000 (I think one1 + two1 should suffice). Then you try to fill the new array by looping through it two elements at a time:
for (int i = 0; i < combo.length - 1; i += 2) {
So i is 0, 2, 4 etc. through 19998 (the last even number before 20000). Except when it gets 10000, you try to pick out one[i], that is one[10000], which is outside the one array. This gives the ArrayIndexOutOfBoundsException.
How I found out? The stack trace gives a line number. The line it mentions is
combo[i] = one[i];
It also mentioned the number 10000, so I knew this was the value of i at this point.
I think that what you were trying to do, was fill elements 0 from one and two into elements 0 and 1 of combo, I think it works so far. Then you wanted to fill element 1 from each array into elements 2 and 3; but since you have added 2 to i, you fill in element 2 from each source array and never use element 1 from them. Or any element from odd indices.
Before you mend that problem, allow me to mention one more thing. I think with your logic, input arrays 2 5 and 11 30 will come out as 2 11 5 30. This doesn’t fulfil “with all elements in order, lowest to highest”. So I think you should think your algorithm over.
the code exist many logic error,
as for Runtime Error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10000 at..
the problem is here:
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
the i from 0 to 19999 and the index of a,b is from 0 to 9999, and the code exist other simple logic problem. Please check it again.
Homework questions are very frowned upon, but still, Java is a relatively easy language. If your program is throwing a RuntimeException, you just have to read what the problem is.
In this case, it seems a loop iterates more times than it should, and you are accessing other memory space. Give it a few reads with the info provided by the error trace in mind.

How do I keep an Int variable positive or 0 in Java

I have created a while loop in which a variable's value decreases each time. How do I program the variable such that it's value never goes negative?
for example if it's currently equal to 3
and the input is 5 I want to program it so that 3-5 gives me zero not -2 .
// myVar is your variable and inputVar is the input variable
myVar= (myVar > inputVar) ? myVar-inputVar : 0;
The condition (myVar > inputVar)is tested. If it is true the first value, myVar-inputVar, is returned. If it is false, the second value, 0, is returned
you can check the value whether it is negative or positive
int result = var1 - var2 ;
if(result<0){
// print zero
}
else{
// print result
}

Java - for() loop and arrays

The next question is from test that I've done.. I've run the code on BlueJ and don't get why the return value is 5...
public int mystery(int[] myStuff, int num) {
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
myStuff = 2, 4, 0, 1, -6, 3, 8, 7, 5
num = 4
In the test I wrote - 0. Why 5? I don't get it!
What is the part of the
`return -1`
?
You're getting 5 because that is the index of the first element in the array whose value is less than 4 (when starting from the last element and working towards the first). Note that you have:
return k;
...where k is your array index. If you wanted to get the value at that index, you should do:
return myStuff[k];
Here's a simple example that shows that your result is in fact correct: http://ideone.com/7byIY
And the return -1; is just saying "if no elements are less than the specified number then return a value of -1 to indicate that no match was found". This is not an uncommon practice (returning an intentionally chosen, invalid value to indicate that there is no result).
It returns five because that's the index of 3 in your input array, which is the first number strictly smaller than 4 starting from the end of your array.
return -1; would be executed if none of the items in your array satisfy the "strictly smaller than num" criteria.
The function returns the largest index in the array corresponding to a value less than the target. This is accomplished on arbitrary arrays by scanning from the back and returning the first index corresponding to a value less than the target. In your example, 3 < 4 at index 5, so this is the correct answer. If no values smaller than the target are found, -1 is used as a sentinel value to indicate the algorithm failed to find a valid answer.
That function gives the position of the last number in the first argument that's smaller than the second argument (or -1 if all the numbers are larger than the second argument; -1 is a special value with no chance of ambiguity because there's no position -1).
That number is 3 and its position is 5 (starting with 0).
This function just searches for the last value in the array which is greater or equal than num. Let's compute the check myStuff[k] < 4 for all values:
0 1 2 3 4 5 6 7 8 // k
2 4 0 1 -6 3 8 7 5 // myStuff[k]
true false true true true true false false false // myStuff[k] < 4
The last index for which myStuff[k] < 4 is true is obviously 5, so that's the correct answer.
return -1 is needed so that the function returns a value, even if all elements of myStuff are larger than num. For example, with num = -99, the result would be -1.
your return-1 doesn't mean anything for the parameters you have passed here.
as the condition is true for value 3 so it returns the value of k, which is nothing but 5 bt that movement. this is because you are iterating backwards.
mystery(myStuff=[2,4,0,1,-6,3,8,7,5], 4)
then the for begins
for (int k = 8; k>=0; k--)
if ( myStuff[8]=5 < 4) - NO
2nd iteration
k = 7 if (7 < 4) - NO
... so on
k = 6 if (8 < 4) - NO
k = 5 if (3 < 4) - YES - so return k = 5
The last part means:
if myStuff does not have any value < num then it returns -1

Can someone please explain how this implementation works? Also, can it be made better? How?

public class Main {
public static void main(String args []){
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0 (same for all other variables)
int number = 1;
int maxLimit = 10000000;
boolean[] sieve = new boolean[maxLimit]; //creates new boolean array called sieve and allocates space on the
//stack for this array which has maxLimit spaces in it
for ( int i = 2; i < maxLimit; i++ ) { //for statement cycling from 2 to 10000000, does not execute the rest
//of the block if the boolean value in the array is true
if ( sieve[i] == true ) continue;
numberOfPrimes++; //otherwise it increments the number of prime numbers found
if ( numberOfPrimes == 10001 ) { //if 10001st prime number is found, break from loop
number = i;
break;
}
for ( int j = i+i; j < maxLimit; j += i ) //do not understand the point of this loop logically
sieve[j] = true; //testing if the value in the array is true again?
}
System.out.println("10001st prime: "+ number);
}
}
I don't really understand what is going on in this program and was hoping somebody could explain it to me? I have commented the specific lines causing me trouble/what I understand lines to be doing. Thank you very much for all the help! :)
Make yourself familiar with Eratosthenes' Sieve algorithm. Wikipedia even has animated gif demonstrating the process. And your code is just a straightforward implementation of it.
Yes, this is your basic implementation of Eratosthenes' Sieve. There are quite a few ways in which you can improve it, but let's go over the basic principle first.
What you are doing is creating an array of boolean values. The INDEX in the array represents the number which we are testing to see if it is a prime or not.
Now you are going to start checking each number to see if it is a prime. First off, the definition of a prime is "all numbers divisible ONLY by itself and 1 without fractioning".
for ( int i = 2; i < maxLimit; i++ )
You start with the INDEX 2 (the number 3) because depending on your definition, 1 and 2 are always prime. (Some definitions say 1 is not a prime).
if ( sieve[i] == true ) continue;
If a number has been marked as a non-prime previously, we don't bother with the current iteration.
numberOfPrimes++;
if ( numberOfPrimes == 10001 ) {
number = i;
break;
}
If the INDEX we are at currently has not been marked as being a prime, it has to be one, so we increment the number of primes we have found. The next piece of code I'm assuming is part of the requirements of the program which states that if 10001 primes have been found, the program must exit. That part can be left out if you actually want to check for primes up to the maximum number defined in stead of for a specific number of primes.
for ( int j = i+i; j < maxLimit; j += i )
sieve[j] = true;
This is where the actual magic of the sieve starts. From the definition of a prime, a number cannot be a prime if it is divisible by anything other than itself and 1. Therefore, for any new number we find that is a prime, we can mark all it's factors as NOT being prime. For example, the first iteration of the for loop, we start with 3. Because sieve[2] is false (have not visited before), it is a prime (AND 3 IS A PRIME!). Then, all other factors of 3 CANNOT be primes. The above mentioned for loop goes through the entire sieve and marks all factors of 3 as false. So that loop will do: sieve[5] = true; sieve[8] = true ... up until the end of the sieve.
Now, when you reach the first number greater than the maximum defined initially, you can be certain that any number that has a factor has been marked as not being a prime. What you end up with is a boolean array, where each index marked as false, represents a prime number.
You can probably get a much better description on wikipedia, but this is the jist of it. Hope it helps!
for ( int j = i+i; j < maxLimit; j += i ) //dont understand the point of this loop logically
sieve[j] = true; //testing if the value in the array is true again ?
This is not a testing, but rather a setting. This loop is setting all the items in the array with indexes multiple of i to true. When i is 2, then the items 4, 6, 8 ... will be set to true. When i is 3, the items 6, 9, 12 ... will be set to true and so on.
And as you can deduce by the first if,
if ( sieve[i] == true ) continue;
... all the items that are true correspond to non-prime numbers.
I find the easiest way to understand something is to deconstruct it. Therefore, lets go through the loop a few times, shall we?
Dawn of the First Iteration
− 9999998 Values Remain −
i = 2
sieve[2] is false, so we keep going in the current iteration.
numberOfPrimes = 1 and thus we continue processing
Set every multiple of 2 to true in sieve[].
Dawn of the Second Iteration
− 9999997 Values Remain −
i = 3
sieve[3] is false, so we keep going in the current iteration.
numberOfPrimes = 2 and thus we continue processing
Set every multiple of 3 to true in sieve[].
Dawn of the Third Iteration
− 9999996 Values Remain −
i = 4
sieve[4] is true (from first iteration). Skip to next iteration.
etc... but in this case, the moon doesn't crash into Termina.
The loop in question isn't checking for true values, it's setting true values.
It's going through each multiple of the prime and marking it as non-prime up to maxLimit. You'll notice there's no other math in the code to determine what's prime and what's not.
This is the algorithm to find the prime numbers between 1 and the maximum limit given.
And the loop added 2nd is to make true for the number which is divisible by any other number. so for the first outer loop all the number divisible by two ll be set to true then divisible by 3 then by 4 and so on.. and the numbers for which the boolean array contains false are the prime numbers.

Categories