Reputation: 1294
I have a specified array. I need to pass them all through the while loop and everytime there is a change in increasing or decreasing order, I add 1 to Totalrun. e.g. 2,3,7 are all increasing, but if the next number in the array is less than 7, then it adds 1 to the run, to start a new run. A run is a list of contiguous numbers that are either all increasing (ups) or all decreasing (downs).
public class run {
public static void main(String[] args) {
boolean prevgrad;
int[] number = {2, 3, 7, 4, 5, 1, 12, 14, 9, 28};
int Totalrun = 1;
for (int i = 0; i < number.length - 2; i++) {
int prevnum = number[i];
int currnum = number[i + 1];
if (currnum > prevnum) {
prevgrad = true;
if (currnum > prevnum) {
if (prevgrad = true) {
} else {
Totalrun = Totalrun + 1;
prevgrad = false;
if (currnum < prevnum) {
if (prevgrad = false) {
} else {
Totalrun = Totalrun + 1;
}
prevgrad = false;
break;
System.out.println(Totalrun);
}
}
}
}
}
}
}
error:
run.java:30: error: unreachable statement
System.out.println(Totalrun);
^
1 error
Upvotes: 0
Views: 101
Reputation: 638
I think I got it, here it is not for you to copy, but to learn from. From here on out, I would HIGHLY recommend you go and watch some videos or even read a good book on Java. Posting every question you have on stackoverflow doesn't help near as much as a good book on programming.
public class Test {
public static void main(String args[]) {
int[] number = {2,3,7,4,5,1,12,14,9,28}; // 1, 4, -3, 1, -4, 11, 2, -5, 1 <- These are differences from curr - prev
int totalRun, incRun = 0, decRun = 0; // Not 1, what if theyre all increasing/decreasing? Run never goes to 1.
for (int i = 0; i < number.length - 1; i++) {
int prevnum = number[i];
int currnum = number[i+1];
int difference = currnum - prevnum;
if (difference > 0)
incRun++;
else
decRun++;
}
if (number[1] > number[0])
totalRun = incRun;
else
totalRun = decRun;
System.out.println("Total run: " + totalRun);
}
}
Upvotes: 1
Reputation: 159
You can't access an array's values in that fashion (at least not that I know of). There are multiple ways you could use, I personally would use an array for
loop for this example.
prevNum = 0;
for (int currNum: Number) {
if (prevNum > currNum) {
prevgrad = "up";
... rest of the code;
}
}
The reason for this is in this type of for loop, the value of currNum
is equal to whatever the value of the array is in that iteration.
The complete code would be:
int prevNum = 0;
int totalRun = 0;
for (int currNum: Number) {
if (prevNum > currNum) {
prevgrad = "up";
}
else {
totalRun++;
prevgrad = "down";
}
prevNum = currNum;
}
Upvotes: 0