How to use a variable outside of a for loop [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 7 years ago.
Improve this question
I'm trying to convert multiple strings into integers and then print use each one of them outside of the for loop.
This is my for loop:
for (int i = 0; i < parts.length; i++) {
int p1 = Integer.parseInt(parts[i]);
}

If you want to be able to access all of the integers you are parsing after the loop:
int[] pValues = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
pValues[i] = Integer.parseInt(parts[i]);
}
// at this point you still have access to the pValues array

In order to use anything outside a for loop (or any other scope, for that matter) you must declare that variable in the scope where you wish to use it:
int p1 = -1;
for (int i = 0; i < parts.length; i++) {
p1 = Integer.parseInt(parts[i]);
}
Note that in situations like the above, where a loop sets a single value, a very common thing is to break the loop right after setting the value. Obviously, the value should be set conditionally, otherwise the purpose of the loop would be defeated:
int p1 = -1;
for (int i = 0; i < parts.length; i++) {
if (someCondition()) {
p1 = Integer.parseInt(parts[i]);
break;
}
}

Any variables created inside of a loop are LOCAL TO THE LOOP. This means that once you exit the loop, the variable can no longer be accessed! This includes any variables created in the loop signature.
Read more: http://www.java-made-easy.com/variable-scope.html#ixzz3TZ6obLXK
int secondp1 = 0; // Define your variable outside your loop
for (int i = 0; i < parts.length; i++) {
secondp1 = Integer.parseInt(parts[i]);
}
//so you can use it here.
System.out.println(secondp1 );
You can see this to check out variable scope and lifetime.

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 have a loop that displays 10 values: 1.0, 1.1,1.2, etc. how can I put those values into 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 6 years ago.
Improve this question
I have a loop that displays 10 values: 1.0, 1.1, 1.2, etc.:
int i = 0;
int x = 10;
for(i;i>x;i++)
{
System.out.println(x);
}
but instead of displaying the values, I want to put them in an array. How do I do that?
How about:
// You want x ints.
int x = 10;
// Make an array big enough to hold x ints.
int[] array = new int[x];
// Loop x times.
for(int i = 0; i < x; i++) {
// Put the next number into the array.
array[i] = i;
}
first your way in writing for loop is need to be more clean
it should :
for(int i=0; i > x; i++){
System.out.println(x);
}
second your boolean condition in for loop isn't true because x=10 is always bigger than i=0 so it won't print any thing.
third to put the values in array :
simply define array : int[] numbers = new int[size of array];
then put each value inside the index i of array :
numbers[i] = i;
finally for loop will be like:
for(int i=0; i < x; i++){
numbers[i] = i;
}

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

Difference between prefix and postfix operators in different situations [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 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!

Categories

Resources