I have a program that grabs a file containing boolean values, and I'm counting the number of false values until it reaches a true value. Then, when it encounters another false value it counts them again. I have a lower threshold and a higher threshold for the number of false values, and I need to increment a counter only once when within this range. This is not a homework assignment, by the way.
private static int readBooleanValues(File textFile, int higher, int lower) throws FileNotFoundException {
Scanner scanner = new Scanner (textFile);
int counter = 0;
int secondaryCounter = 0;
while ( scanner.hasNext() ) {
String value = scanner.next();
if ( value.equalsIgnoreCase("false") ) {
counter++;
if ( counter >= lower && counter <= higher ) {
secondaryCounter++;
}
} else if ( value.equalsIgnoreCase("true") ) {
counter = 0;
}
}
return secondaryCounter;
}
If I understand your question correctly, you want to do what #WonderWorld suggested, and also replace
if ( counter >= lower && counter <= higher ) {
secondaryCounter++;
}
by
if (counter == lower)
secondaryCounter++;
if (counter == higher+1)
secondaryCounter--;
This increments secondaryCounter only once, when it first enters the range. If it later turns out that the string of false values is too long (when counter reaches higher+1), the value of secondaryCounter is corrected.
Change this:
if ( counter >= lower && counter <= higher ) {
secondaryCounter++;
}
to
if ( counter >= lower) {
secondaryCounter++;counter=0;
}
Now your range will not be in reach, counter will stay zero while Scanner is reading true values, and you can start again. Although if having too many false values invalidates the count, you will need to take further action.
Or you could place the secondaryCounter in the true part:
if ( value.equalsIgnoreCase("false") ) {
counter++;
}
} else if ( value.equalsIgnoreCase("true") ) {
if ( counter >= lower && counter <= higher ) {
secondaryCounter++;
}
counter = 0;
Related
int count = charFreq.get(guessChar);
int matchedChars = updatedCharFreq.get('_');
if (updatedKeyVals.contains('_')) {
if (count == matchedChars) {
;
}
if (count < matchedChars) {
;
}
else {
count = count - matchedChars;
}
Method works if count < matchedChars, and also the else statement. It just skips past the if equality statement. I have been trying to figure it out, but just can't seem to.
As commented, you neglected to chain the first if with an else.
I suggest accounting for all cases explicitly plus an extra final case that should never be reached. The extra check is for defensive programming, to guard against editing errors.
if (count == matchedChars) {
// No code needed here.
} else if (count < matchedChars) {
// No code needed here.
} else if (count > matchedChars) {
count = count - matchedChars;
} else {
throw new IllegalStateException( … ) ; // Should never reach this point.
}
It seems you only care about the case where the first number is bigger than the second. So we could shorten this code.
if (count > matchedChars) {
count = count - matchedChars;
}
Alternatively, you can use the static method Integer.compare. To quote the Javadoc:
Returns: the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y
if( Integer.compare( count , matchedChars ) > 0 ) {
count = count - matchedChars;
}
I'm trying to print following pattern:
0
11
0
222
0
3333
0
222
0
11
0
I want to achieve this by using recursion and a loop inside said recursive method, which gets one integer value passed. The int value determines how far this pyramid pattern goes. In the example above the int value would be 3.
I managed to get the bottom half, but I have no idea to get the upper half.
if (arg != 0) {
System.out.println("0");
for (int i = 0; i <= arg; i++) {
System.out.print(arg);
}
System.out.println();
print(arg - 1);
}
How would I be able to somehow implement some increment, which turns to a decrement to this recursion? Since I'm thinking this would be how I could achieve the above pattern.
Thank you very much in advance!
You can pass two arguments. The Max value and start value which will be zero and
then increment start value until reaches max
then decrement Max until reaches zero
call--> printline(3);
private static void printline(int input, int... vars) {
if (input == 0) {
System.out.println(0);
return;
}
int start= vars.length > 0 ? vars[0] : 0;
start++;
System.out.println("0");
for (int i = 0; (i <= start && i <= input); i++) {
System.out.print(start >= input ? input : start);
}
System.out.println();
if (start >= input) {
input--;
}
printline(input, start);
}
}
This will count how many times the while loop ran when true, however, I am trying to count how many times the num==0 test is performed. The num integer will change.
int counter = 0;
while (num == 0) {
doSomething();
counter ++;
}
This is an alternative I came up with, but seeking a better way to do it.
int counter = 0;
do {
if (num == 0) {
doSomething();
counter++;
} else {
counter++;
}
} while (num == 0);
Given the loop:
while (num == 0) {
doSomething();
counter ++;
}
The check num==0 will be performed once for every iteration, then once more after the last iteration. That last check is the one that prevents the while from being executed again.
So if counter is equal to 3, that means that we had 3 full iterations of the loop (3 checks whether num==0), followed by a fourth check that prevented us from going into the loop again.
It isn't clear to me what your second code snippet is trying to achieve.
if (num == 0) {
doSomething();
counter++;
} else {
counter++;
}
Is 100% equivalent to
if (num == 0) {
doSomething();
}
counter++;
And after every iteration of the do...while() there will still be a check for num==0 due to the loop condition.
If you want to count the number of times a particular if condition is checked (inspected) within a while loop then place a counter variable (that increments by 1: counter++;) directly above that if statement line within the loop since any conditional statement can potentially abruptly break out of or continue the loop within its code block if that particular condition is true.
This counter variable will need to have been declared and initialized to 0 above the while loop. Here is an example:
int counter = 0;
while (num == 0) {
if (doSomething == true) {
continue; // counter can not increment. Goes to next iteration.
}
if (doOtherThing.equals("no") {
break; // counter can not increment. Exits loop.
}
counter ++; // counts the number of times the following IF was checked.
if (n == 0) {
doSomthingCool();
num++; // increments num to 1 and loop will exit on next iteration attempt.
}
}
The above counter simply indicates that the IF condition following the increment of that counter will definitely be inspected...not found to be true and its' code block entered and run. It basically indicates that the condition will definitely be looked at.
This is fine and well until you start dealing with else if. What if you wanted to know if the ELSE IF was checked? Was the IF inspected or the ELSE IF? You still don't want to know if the condition was true and the code block for that statement was entered, you just want to know if the condition was looked at and checked.
One way to overcome this situation is to apply the counter directly into the condition for that statement. This can be done but the counter condition portion should always be equal to true and be the first condition encountered followed by && (AND) within the overall conditional statement, this way all other conditions will be checked in their original sequential order:
if ((ifCounter == ifCounter++) && someNum < 3) { ... }
else if ((elseCounter = elseCounter++) && someNum < 10) { ... }
Here is a runnable example:
int num = 0;
int counter = 0; // The Overall iteration counter
int doSomethingCounter = 0; // The doSomething condition counter
int doSomeOtherThingCounter = 0; // The doOtherThing condition counter
int ifCounter = 0; // The IF someNum condition counter
int elseIfCounter = 0; // The ELSE IF someNum condition counter
int someNum = 0;
boolean doSomething = true;
String doOtherThing = "yes";
while (num < 10) {
counter++;
if ((doSomethingCounter == doSomethingCounter++) && doSomething == true) {
doSomething = !doSomething;
continue; // Counters can not increment. Goes to next iteration.
}
if ((doSomeOtherThingCounter == doSomeOtherThingCounter++) && doOtherThing.equals("no")) {
break; // Counters can not increment. Exits loop.
}
// Counts the number of times the following IF condition was checked.
if ((ifCounter == ifCounter++) && someNum < 4) {
someNum = doSomethingCool(someNum);
}
// Counts the number of times ELSE IF condition is checked.
else if ((elseIfCounter == elseIfCounter++) && someNum > 0) {
/* increments num by 1 until it reaches 10 then loop
will exit on next iteration attempt. */
num++;
}
}
System.out.println("The WHILE loop has done a total of: " + counter + " iterations.");
System.out.println("The doSomething IF condition was checked: " + doSomethingCounter + " times.");
System.out.println("The doOtherThing IF condition was checked: " + doSomeOtherThingCounter + " times.");
System.out.println("The someNum IF condition was checked: " + ifCounter + " times.");
System.out.println("The someNum ELSE IF condition was checked: " + elseIfCounter + " times.");
When the above code example is run the console window will display:
The WHILE loop has done a total of: 15 iterations.
The doSomething IF condition was checked: 15 times.
The doOtherThing IF condition was checked: 14 times.
The someNum IF condition was checked: 14 times.
The someNum ELSE IF condition was checked: 10 times.
int num = 0;
int counter = 0;
while(num==0) {
if (num == 0) {
doSomething();
} else {
}
counter++;
//if the counter inc then the above condition statement should been executed.Make sure this doesn't take break into consideration.
}
I am working on a problem related to ISBN book codes. I need to make the program so that input is given with 9 digits of the needed 10 digit code. The 10th one is a '?'. The program needs to output the appropriate number. I started by splitting the input String into two sub-Strings wherever '?' is detected.
My question is HOW TO GET EACH INTEGER FROM THE INPUT STRING (SO I CAN MULTIPLY THOSE INTEGERS WITH CERTAIN NUMBERS TO GET THE FINAL ANSWER)
for example : Input String is: '01234?6789'
How do I extract all the digits from this string, so that all mathematical operations are possible to be performed on these digits
Would something like this help you?
private static int getCharAsInt(int x, String number) {
if ((int) number.charAt(x) - 48 > 9){
//do something if the char is "?"
//maybe return -1 to know its not a number you can use
return -1;
}
else //return the char as an int
return (int) number.charAt(x) - 48;
}
This method will return the char of the String "number" at position x as an int and will return -1 when it finds the "?". Not that you can make it do anything else you like when you find the "?".
Anyway when you call it like that :
String string = "01234?6789";
for(int i = 0; i < string.length(); i++)
System.out.print(getCharAsInt(i, string) + " ");
The output will be:
0 1 2 3 4 -1 6 7 8 9
Of course the method returns an int so you can call it and perform any operations you want to get the final answer.
Hope this helps
This contains a few statement sequences you should study. See the comments.
// checks whether the ten digits in the int[] make up a valid ISBN-10
private boolean isValid( int[] digits ){
int sum = 0;
for( int i = 0; i < digits.length; i++ ){
sum += (10 - i)*digits[i];
}
return sum % 11 == 0;
}
// Expect a string with 9 or 19 digits and at most one '?'
public String examine( String isbn ){
if( isbn.length() != 10 )
throw new IllegalArgumentException( "string length " + isbn.length() );
if( ! isbn.matches( "\\d*\\??\\d*" ) )
throw new IllegalArgumentException( "string contains invalid characters" );
// Now we have 9 or 10 digits and at most one question mark.
// Convert char values to int values by subtracting the integer value of '0'
int qmPos = -1;
int[] digit = new int[10];
for( int iDig = 0; iDig < isbn.length(); iDig++ ){
char c = isbn.charAt(iDig);
if( c == '?' ){
qmPos = iDig;
digit[iDig] = 0;
} else {
digit[iDig] = c - (int)'0';
}
}
// If qmPos is still -1, there's no '?'
if( qmPos == -1 ){
// Is it a valid ISBN-10?
if( isValid( digit ) ){
return Arrays.toString( digit );
} else {
throw new IllegalArgumentException( "not a valid ISBN" );
}
}
// Which digit can replace '?'?
for( int probe = 0; probe <= 9; probe++ ){
digit[qmPos] = probe;
if( isValid( digit ) ){
// found it - return the completed ISBN-10
return Arrays.toString( digit );
}
}
// Failure
throw new IllegalArgumentException( "no digit completes an ISBN" );
}
I am trying to increment the counter by whatever number the user inputs. I have been at this for almost an hour now and cannot figure it out. Any ideas?
Here's what I have:
if (starting < ending) {
while (i < ending) {
++i;
System.out.println(i);
}
}
else if (starting > ending) {
while (i > ending) {
--i;
System.out.println(i);
}
}
else {
System.out.println(i);
}
No matter what increment is entered, it starts at the starting number and counts up or down by 1.
It counts up or down by 1 because of ++i and --i. The ++ and -- operators are equal to i = i + 1 and i = i - 1, or i += 1 and i -= 1 respectively.
In order to increase or decrease by the amount a user enters, use i = i + userInput and i = i - userInput, or i += userInput and i -= userInput.
For example:
int userInput = 4;
if(starting < ending) {
while(i < ending) {
i = i + userInput;
System.out.println(i);
}
// ... etc
}
In your while loop, you could put:
while (i > ending){
i -= numberUserInput;
}
This will reassign i's value with itself plus the variable that holds the number the user input (named whatever you want). For addition, you could use += instead of -=.