Difference between prefix and postfix operators in different situations [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have gone through all the questions in this forum that are corresponding to this topic, and I felt to raise a different question as this question is not answered clearly. Here is my scenario:
I have this class Test1:
public class Test1 {
public static void main(String args[]) {
int i=0, j=2;
do {
i= i+1;
j--;
} while(j>0);
System.out.println(i);
}
}
Now this is my question:
a) If I replace the increment operation of 'i= i+1' with ++i, I get the desired output as
1
2
But if I replace the increment operation of 'i= i+1' with i++, I get the desired output as
0
0
I do understand the difference of using prefix and postfix operators in for loop, but why is the value not getting incremented at all in do-while loop?

Using i = i++; will never change i value.
Use just:
i++;
Why? because:
i = i++;
is similar to doing something like this:
temp = i; // temp is 0.
i = i+1; // increment i
i = temp; // assign temp (which is 0) to i.
Take a look at a similar post-increament question and even another one.

++i
This will increment i, then return it.
i++
This will return i, then increment it.
Example
Here is a link to an ideone example of this.
int i = 5;
System.out.println(i++);
// Outputs 5
int j = 5;
System.out.println(++j);
// Outputs 6.

x = i++; is a shortcut for x = i; i = i + 1;
x = ++i; is a shortcut for i = i + 1; x = i;
that's it.

Actually in your sample, there should be no difference between i++ and ++i, if you replace i = i+1 by one of two. Chris noted the difference correctly, I'll just add a sample, where this is important:
int i = 0;
method(i++);
Will call method with the original value of 0 and increment i afterwords. In method, however, you'll see the original value 0.
int i = 0;
method(++i);
Will increment i and then call method. So in method you'll get the value of 1. That does not change the fact that after method, i has the value 1 in both cases.
Others have noted correctly that
i = ++i;
and
i = i++;
are different things actually!

Related

Show numbers not incluided in an Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I've an issue that I couldn't fix, I tried different ways. I filled an Array with ok 100 positions with randoom numbers (Range: 1-100). Then I've to show by console the numers that aren't incluides in the array. I try two loopes nested but it didn't work neither.
int arraySize = 100, aux=0;
int numeros [] = new int [arraySize];
for (int i = 0; i < numeros.length; i++) {
numeros[i] = (int) ((Math.random()*100)+1);
Here, Somebody know how to get it? Thanks
I'd just stream all the numbers and check which ones aren't included in the array. Note that in order to get better performance it may be useful to convert the array to a Set, but it isn't strictly required:
Set<Integer> existing = Arrays.stream(numeros).boxed().collect(Collectors.toSet());
IntStream.rangeClosed(1, 100)
.boxed()
.filter(i -> !existing.contains(i))
.forEach(System.out::println); // or collect them to use later
Instead of nested for loops, for better performance, try one of the following options:
Sort the array using Arrays.sort(numeros), then iterate and print missing values whenever a gap is detected.
Add all the numbers to a HashSet<Integer>, then iterate 1-100 and print any value not found in the Set.
Since your question is obviously an exercise or test, I'll leave the actual code writing to you.
Well I could fix it with an counter, It was easier more than i think, but in stressfull peaks we don't think in a right way. I'll let the Code below.
int numeros [] = new int [arraySize];
for (int i = 0; i < numeros.length; i++) {
numeros[i] = (int) ((Math.random()*100)+1);
}
//Loop to show not numbers in the array
for (int i = 0; i < numeros.length; i++) {
for (int j = 0; j < numeros.length; j++) {
if (i==numeros[j]) {
cont++;
}
}
if (cont==0) {
System.out.println(i);
}
cont=0;
}

How can i count how many times the keywords user enter is the used in the essay. its doesn't check on the entire keyword [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public static int keywordsChecker(String essay,String key) {
int count = 1;
String[] k=key.split(",");
for (int i = 0; i < k.length-1; i++) {
if (essay.contains(k[i])) {
count++;
}
}
return count;
}
To take into account that each keyword searched for may occur more than once, and to count such occurrences, you may use this inside your for loop:
int indexOfOccurrence = essay.indexOf(k[i]);
while (indexOfOccurrence > -1) {
count++;
indexOfOccurrence = essay.indexOf(k[i], indexOfOccurrence + 1);
}
There are a couple of other issues in your code: I believe you need to initialize count to 0 (not 1). And to count also the last keyword in key your for loop should be for (int i = 0; i < k.length; i++) (without subtracting 1 from k.length). If you want, using <= would also work: for (int i = 0; i <= k.length-1; i++), but this is non-standard, so I would not recommend it.

I want to hold the value of a variable in java outside the loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having a global variable and I want to concatenate some value to this variable in a for loop and want the value outside of a for loop.
But the problem is whenever the for loop starts it's next iteration value of variable is lost.
my code
function hello() {
StringBuffer Id = new StringBuffer(20);
Id.append("");
for (i = 1; i < 10; i++) {
Id.append(i);
}
System.out.println(Id);
}
You need System.out.println(id); based on your comment that has your code.
You just need to return id from your method to caller to hold the value.
String[][] matrix = { {"1", "2", "3"} };
String[] y = {"TEST" ,"BUG"};
int a = 0;
int value = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value); //this is OK it print me 3 values
}
}
System.out.println(value);
Declaring variables inside or outside of a loop

finding odd numbers in java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I try to print the odd numbers in Java that are inside the array but this algorithm doesn't work ... May someone help me ?
The printing result is that :
"Exception in thread "main" .java.lang.ArrayIndexOutOfBoundsException: 7
at JavaArray.main(JavaArray.java:12)"
Code :
public class JavaArray {
public static void main(String[] args) {
int[] myArray = {1,3,4,5,8,9,10};
int i = 0;
for(i = 0; i < myArray.length; i++); {
if(myArray[i] % 2 == 1) {
System.out.println(myArray[i]);
}
}
}
}
Remove the semi-colon that is terminating your for loop
for (i = 0; i < myArray.length; i++);
^
Because you have placed semicolon after for loop, variable i increments till length of array(here 7). After that loop ends and you are trying to access myarray element through i which is 7 so it is giving out of bound exception.
Besides the extra ; you need to remove, you can consolidate by declaring the int in the loop declaration:
for (int i = 0; i < myArray.length; i++) {
.
.
.
}
Beside #Reimus point , you can also do it like below , sort the array if it's not sorted yet, in your case it is sorted . FYI, Instead of Collections.sort which is above O(N) complexity use a Hash Set.
public static void main(String[] args) {
int[] myArray={1,3,4,5,8,9,10};
Arrays.sort(str);
for (int i = 1; i < myArray.length; i++) {
if (str[i] == str[i - 1]) {
System.out.println("Dupe-num: " + str[i];
}
}
}

The value of the loop counter of a for loop is one larger than I expect after exit from the loop [closed]

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 have a simple for loop, which lets the loop counter, i go up to 5.
int i;
double n = 1 / 2;
for (i = 2; i <= 5; i++) {
n = n + 1.0 / i;
}
System.out.print(i);
So I expect the value of the counter to be 5 after the loop finishes. But the value is 6, nit 5. Why is that?
Thanks
Because you are incrementing i value as i++ in for{..} loop
for (i = 2; i <= 5; i++)
^ here
In for loop after checking the condition, body part will be executed
after that increment or decrement will be done
Process will be
<----
1step 2step 4step
for (i = 2; i <= 5; i++){
/*body part*/
3step
}
After 4th step it will moves to check 2nd step i.e. condition part
So thats why it prints the i value as
6
The for loop:
for (i = 2; i <= 5; i++) {
// code
}
which has condition i <= 5 and the condition will be false when i = 6 and the loop breaks, goes to the print line.
Thanks for reminding me my first time programming experience, When I used to write a code a = 5 and printed it to see what it shows in the console. :)
The i++ is the same as saying i = i + 1. In this case you can also use ++i and get the same result.

Categories

Resources