i need help on a verification on a string
I have to write a method that verify if 2 parameters of the method have the same length and if the second one have numbers between 0 and 3.
Let's see what i wrote :
public static boolean coupEstValide( String combinaison, String coup ){
boolean res = true;
if(combinaison.length() == coup.length()){
int i = 0;
while(i < coup.length() && res == true){
char t = coup.charAt(i);
if(t <= 0 && t >= 3)
res = false;
i++;
}
}
return res;
in my opinion, this should work... But if i do this :
coupEstValide("555", "104");
it should tell me false but it it's telling me it's true.
Do you guys see what's wrong ?
Thanks
When you compare Character with an integer actually ASCII value of that character gets compared with that integer. That's why you keep getting true.
So as already suggested in the comments you should compare it either as if(t >= '0' && t <= '3') or use any Utility method of java.lang such as Character.compare(char lhs, char rhs).
Hope this would be helpful.
Enjoy!
A few of problems in your code:
If the lengths are different, you are still returning true!
Strings are composed of characters. Their value is their character code. 0 to 3 are 48 to 51, respectively. Use character constants not integer constants: if (t == '0') will check if t is the character "0".
Your logic for the comparison isn't right anyways. Using your original (incorrect) example with integers, and correcting from <= and >= based on your comments: if (t < 0 && t > 3) will never be true, t cannot simultaneously be less than 0 and greater than 3. I'll leave the correct boolean statement as an exercise to the reader (hint: or).
Alright, i fixed the problem.
So as you said, i should've use
if(t < '0' || t > '3')
And to fix the problem of the time both are not the same size, i added an else.
So the full code is that :
public static boolean coupEstValide( String combinaison, String coup ){
boolean res = true;
if(combinaison.length() == coup.length()){
int i = 0;
while(i < coup.length() && res == true){
char t = coup.charAt(i);
if(t < '0' || t > '3')
res = false;
i++;
}
}
else
res = false;
return res;
}
Thanks for your help guys !
This would never true. A number can not be less and equal to zero and at the same time greater and equal to 3.
if(t <= 0 && t >= 3)
If you want to evaluate whether a character is between 0 and 3 you must use this:
if(t >= '0' && t <= '3')
Now if you want to evaluate if the character is not between 0 and 3 then try this:
if (t <'0' || t> '3')
String coup = "053";
boolean res = true;
int i = 0;
while (i < coup.length() && res == true) {
System.out.println(coup.length());
int t = Integer.parseInt(coup.charAt(i) + "");
System.out.println("T is " + t);
if (t <= 0 || t >= 3) {
res = false;
i++;
}
System.out.println("Value i " + i);
System.out.println("Value of the Res at last" + res);
}
may be this could be helpful try to convert it to the integer
according to your code
String coup = "053";
boolean res = true;
int i = 1;
while (i < coup.length() && res == true) {
System.out.println(coup.length());
//int t = Integer.parseInt(coup.charAt(i) + "");
char t = coup.charAt(i);
System.out.println("T is " + t);
if (t <= 0 || t >= 3) {
res = false;
i++;
}
System.out.println("Value i " + i);
System.out.println("Value of the Res at last" + res);
}
Related
I am making a program that checks to see if an elements positive and negative charges are able to combine to make 0. A thing i want to do is output the reasons why the two elements are not able to combine. But it is more difficult than i expected. for example if sodium were trying to combine with copernicium, it would output this:
Sodium doesn't combine with Copernicium:
Both valence charges have same polarity.
One or more elements is man-made.
but i can not think of a way to implement this into my code.
here is my code:
public void combine(Element element){
if ((element.getValence() > 0 && valence < 0) || (element.getValence() < 0 && valence > 0)) { //one element needs a positive valence, and one needs a negative valence
if (valence != 0 && element.getValence() != 0) { //checks to see if valence is not equal to 0
if (natural == true && element.isNatural() == true) { //checks to see if both elements are natural
for (int x = 1; x <= 4; x++) {//bruteforce the atoms to see if they both add up to 0.
for (int y = 1; y <= 4; y++) {
if ((valence * x) + (element.getValence() * y) == 0) {
System.out.println(name + " combines with " + element.getName() + " to form " + symbol + "" + x + "" + element.getSymbol() + "" + y);
}
}
}
}
}
}
}
Thanks for any help!
The way to do this is to add else clauses for each if that return an appropriate message.
if ((element.getValence() > 0 && valence < 0) || (element.getValence() < 0 && valence > 0)) { //one element needs a positive valence, and one needs a negative valence
{
// the inner tests
}
else
{
System.out.println("The elements are both positive or both negative");
}
}
This should get you started in the right direction.
I'm trying to convert infix to postfix expressions in Java, but somehow it's not reading it in correctly or there might be something wrong with my queue implementation. I tried debugging but I can't see where I went wrong.
Inputs:
2 + 3
4 + 5+6
(7+8) * 9
Output:
2+
4+5
78
Correct outputs would be:
23+
45+6+
78+9*
This is my code:
public int Prior (char c) {
if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return 0;
}
public String convertIn2Post() throws StackException, QueueException{
infix = infix.trim();
for(int i = 0; i < infix.length(); i++) {
if(Character.isDigit(infix.charAt(i))) {
expQueue.enqueue(infix.charAt(i) + "");
}
if (infix.charAt(i) == '(') {
opStack.push(infix.charAt(i) + "");
}
if (infix.charAt(i) == ')') {
while(opStack.peek().equals("(") != true) {
expQueue.enqueue(opStack.pop());
}
opStack.pop();
}
if ( infix.charAt(i) == '+' ||
infix.charAt(i) == '-' ||
infix.charAt(i) == '/' ||
infix.charAt(i) == '*' ) {
if(opStack.isEmpty()){
opStack.push(infix.charAt(i) + "");
}
while(Prior(infix.charAt(i)) <= Prior(opStack.peek().charAt(0))){
expQueue.enqueue(opStack.pop());
if(opStack.isEmpty()){
break;
}
}
}
}
while(!opStack.isEmpty()){
expQueue.enqueue(opStack.pop());
}
for(int y = 0; y < expQueue.size(); y++){
postfix += expQueue.dequeue();
}
return "postfix:: " + postfix;
}
First off, one simple bug in the program is the loop that will dequeue everything. Notice, that each time the loop is run, it checks that
y < expQueue.size()
but, everytime an element is dequeued from the queue, this value is decreasing. So, if the size starts at 6, the program will run for y = 0, size = 6, y = 1, size = 5, y = 2 size = 4, y = 3 size = 3 and that is where it stops. So change this to a while loop:
while(!expQueue.isEmpty())
Next, the algorithm for converting infix to postfix says that if the opstack is empty, to push the operator, which is correct in the code. Then it says that if it is not empty, if the one just found is of higher priority than the one on top of the stack, to add that one to the top of the stack, otherwise pop the top and add the new operator to the stack; this can be done as follows:
if(opStack.isEmpty()){
opStack.push(infix.charAt(i) + "");
}
else
{
String peek = opStack.peek();
if(Prior(peek.charAt(0)) >= Prior(infix.charAt(i)))
{
expQueue.add(opStack.pop());
opStack.push(infix.charAt(i) + "");
}
else
{
opStack.push(infix.charAt(i) + "");
}
}
Code is supposed to do this: Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
The problem: Ran across Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 11 (line number:10)
public int countCode(String str){
int a = 0; // counter goes thru string
int b = str.length()-1;
int counter = 0; //counts code;
if(str.length() < 4) return 0;
else{
while (a <=b){
if(str.charAt(a) == 'c'){
if(str.charAt(a+1) == 'o'){
if(str.charAt(a+3) == 'e'){
counter++;
a= a+3;
} // checks e
else a++;
} // checks o
else a++;
} // checks c
else a++;
}
return counter;
}
}
Here's what I tried to evaluate to get said exception:
countCode("xxcozeyycop") --> EXPECTED RESULT 1
countCode("cozcop") --> EXPECTED RESULT
Your loop goes from 0 to the length of the string (excluded). But inside the loop, you're doing
str.charAt(a+3)
Obviously, if a is length - 1, a + 3 is length + 2, and you're thus trying to access an element outside the bounds of the string.
Side note: you would understand your own code better if you indented it correctly.
Instead of
while (a <=b){
use
while (a <= b - 3){
Reason: Your end sign in the while is the condition that the start of the String "code" is inside the String. However, if a = b - 2, then a + 3 = b + 1 = (str.length() - 1 + 1) = str.length() which is just outside the String.
public int countCode(String str) {
int count = 0;
for(int i = 0; i < str.length()-3; i++)
if(str.substring(i, i+2).equals("co") && str.charAt(i+3) == 'e')
count++;
return count;
}
I seem to get an error when I test running my program, which says java.lang.ArrayIndexOutOfBoundsException: -1
Please can anyone give me some advice on how to fix this?
class MineFinderModel {
public static int MINE_SQUARE = 10;
public static int EMPTY_SQUARE = 0;
int num_of_cols;
int num_of_rows;
int[][] the_minefield;
public MineFinderModel(int n_cols, int n_rows) {
num_of_rows = n_rows;
num_of_cols = n_cols;
the_minefield = new int[num_of_cols][num_of_rows];
}
public boolean addMine(int thisCol, int thisRow) {
if (thisCol >= num_of_cols || thisRow >= num_of_rows)
return false;
if (the_minefield[thisCol][thisRow] == MINE_SQUARE)
return false;
the_minefield[thisCol][thisRow] = MINE_SQUARE;
return true;
}
public int getValue(int thisCol, int thisRow) {
if (thisCol >= num_of_cols || thisRow >= num_of_rows)
return 0;
return the_minefield[thisCol][thisRow];
}
public void addMinesToCorners() {
the_minefield[0][0] = MINE_SQUARE;
the_minefield[0][num_of_rows -1] = MINE_SQUARE;
the_minefield[num_of_cols - 1][0] = MINE_SQUARE;
the_minefield[num_of_cols - 1][num_of_rows - 1] = MINE_SQUARE;
}
}
I guess that it should be in the "addMinesToCorners()" function since you are not testing the boundaries.
What about trying to put some if around you variables ?
if(num_of_cols == 0)
if(num_of_rows == 0)
At initialization, this equals "0", and then "0 - 1" gives "-1". Hence the error.
Hope this helps !
All your methods have the max value check but none of them are checking for a negative value in thisRow and thisCol so the addMine() and getValue() will throw an java.lang.ArrayIndexOutOfBoundsException if any of the arguments to these 2 methods is negative.
You can add a condition like
`
if (thisCol >= num_of_cols || thisCol < 0
|| thisRow >= num_of_rows || thisRow <0)
return false
Arrays are zero indexed so your checks are incorrect, e.g., if num_of_cols is 10 then the last position will be 9 but your check will pass if you pass in 10 as thisCol because it is checking against the initialiser value instead of the length of the array.
Try changing your test to
if (thisCol < 0 thisCol >= (num_of_cols - 1) || thisRow < 0 || thisRow >= num_of_rows - 1))
my code will be display me That is not an acceptable input. if I insert negative number. then proceed to prompt the input. But it continue to calculate. this is part of my code contains something wrong. but i did not see.
public static boolean checkOctal()
{
boolean b = true;
if (oct < 0 && oct > 99999999 )
{
b = false;
System.out.println("That is not an acceptable input.");
}
int tmp;
int tmp1 = oct;
while (tmp1 > 0)
{
tmp = tmp1 % 10;
tmp1 = tmp1 / 10;
if (tmp >= 0 && tmp < 8)
{
continue;
} else
{
b = false;
break;
}
}
return b;
}
you should write
if (oct < 0 || oct > 99999999 )
instead of
if (oct < 0 && oct > 99999999 )
|| stands for or, while && for and.
Actually, I doubt that it's displaying anything. Look at the condition:
if (oct < 0 && oct > 99999999 )
How can a number be negative and largely positive at the same time? You want an "or" condition.
Next, look at what you're doing if you did meet the condition:
{
b = false;
System.out.println("That is not an acceptable input.");
}
You're just keeping going - it will return the right result (false) but it's pointless. You know the result already, so why not just return it?
You want:
if (oct < 0 || oct > 99999999 )
{
System.out.println("That is not an acceptable input.");
return false;
}
Or, better yet, perform the validation earlier (before calling the method) - and throw an exception if the input is invalid. Currently you're giving the same result for "invalid input" as for "valid but non-octal input" which doesn't sound like a good idea to me.
Note that the approach of "return as soon as you know the value" is one I'd take for the rest of the method too - I wouldn't bother with a b variable at all. I'd change your loop to something like this:
int value = oct;
while (value > 0)
{
int digit = value % 10;
if (digit >= 8)
{
return false;
}
value = value / 10;
}
return true;
You don't need to worry about digit being negative, as you've already checked that you started off with a non-negative value.
Additionally, it seems odd that this method doesn't have oct as a parameter. That would make it more self-contained.
You should probably check your boolean logic:
if (oct < 0 && oct > 99999999 )
will never be true - no number is less than zero and larger than 999999 at the same time... The symbol || (logical "or") is what you need instead.
Cheers,