If statement not properly working in java - java

I have a question about if statements and defining integers.
In this code:
if(matches!=null) {t =1;
for (String match : matches) {
if (t == 1 && "one".equals(match)) {
testSound.start();
t = 2;
System.out.println("the value of t is" + t);
} else if (t == 2 && "two".equals(match)) {
testSound.start();
t = 3;
System.out.println("the value of t is" + t);
}
}
If the first if statement executes and returns 2, and then match = "two", will the else if statement work? If not, how would I make it so that when I set t=2, it is actually t=2. Right now it's not working so let me know!

Everything works correctly: the t++ executes before System.out.println, so by the time the t is printed its value is already 2, not 1. If you need 1 printed, move t++ so that it comes after printing.
The second if statement is not executing after that because match is "one", not "two".

You can do System.out.println("the value of t is" + (t++));.
That way you will first print the value of t to the console than add 1 to its value.

Related

Removing a substring from a string, repeatedly

Problem:
Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Explanation/Working:
For Example: t = ab, s = aabb. In the first step, we check if t is
contained within s. Here, t is contained in the middle i.e. a(ab)b.
So, we will remove it and the resultant will be ab and increment the
count value by 1. We again check if t is contained within s. Now, t is
equal to s i.e. (ab). So, we remove that from s and increment the
count. So, since t is no more contained in s, we stop and print the
count value, which is 2 in this case.
So, here's what I have tried:
Code 1:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.
Code 2:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
Thank you in advance :)
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
replace returns a new string; you seemed to think that it alters the given string in-place.
Try adding some simple parameter checks of the strings. The strings shouldn't be equal to null and they should have a length greater than 0 to allow for counts greater than 0.
static int maxMoves(String s, String t) {
int count = 0,i;
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return 0;
while(true)
{
if(s.contains(t) && !s.equals(""))
s = s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
You might be missing on the edge cases in the code 1.
In code 2, you are not storing the new string formed after the replace function.
The replace function replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Try this out:
public static int findCount(String s, String t){
if( null == s || "" == s || null == t || "" == t)
return 0;
int count =0;
while(true){
if(s.contains(t)){
count++;
int i = s.indexOf(t);
s = s.substring(0, i)+s.substring(i+t.length(), s.length());
// s = s.replace(t,"");
}
else
break;
}
return count;
}
String r1="ramraviraravivimravi";
String r2="ravi";
int count=0,i;
while(r1.contains(r2))
{
count++;
i=r1.indexOf(r2);
StringBuilder s1=new StringBuilder(r1);
s1.delete(i,i+r2.length());
System.out.println(s1.toString());
r1=s1.toString();
}
System.out.println(count);
First of all no logical difference in both the codes.
All the mentioned answers are to rectify the error of code 2 but none told how to pass all (14/14) cases.
Here I am mentioning a test case where your code will fail.
s = "abcabcabab";
t = "abcab"
Your answer 1
Expected answer 2
According to your code:
In 1st step, removig t from index 0 of s,
s will reduce to "cabab", so the count will be 1 only.
But actual answer should be 2
I first step, remove t from index 3 of s,
s will reduced to "abcab", count = 1.
In 2nd step removing t from index 0,
s will reduced to "", count = 2.
So answer would be 2.
If anyone know how to handle such cases, please let me know.

How should I format my return statement so I don't double the answer?

private String twoDigits(int value) {
String result = "";
{
if ((mMinute >= 0) && (mMinute <= 9) && (mSecond >= 0) && (mSecond <= 9)) {
tempmin = ("0" + mMinute );
tempsec = ("0" + mSecond );
} else
tempmin = (mMinute + "");
tempsec = (mSecond + " ");
return tempin+tempsec;
This just doubles the output that I'm looking for and I was wondering, whether or not the issue was with the return statement or the actual method.
I need to call back to this method, twoDigits(mMinute)+":"+twoDigits(mSecond) to get the code to display the time, but instead of being able to display 10:09:08 I keep displaying 10:0908:0908
I was wondering how I should fix my code.
Since there are a lot of tiny mistakes in your code, I'll suggest a slightly different approach. Not sure if this method works, in what I assume is Java, but give it a shot:
private String twoDigits(int value)
{
return value <= 9 ? "0" + value : value;
}
This is actually an if/else abbreviation. Return the following: If value <= 9 then add a zero before the value, else the value.
If there's a risk of negative values being received, you could add this:
return (value >= 0 && value <= 9) ? "0" + value : value;
First, there's Paul's comment about the {} after else to encompass both rows. Then, you are not actually using the value received by the function but rather some global variables (mMinute and mSecond). You create but never use result. Furthermore, your if statement says that if both mMinute AND mSecond are between 0 and 9 then both should be fixed. Since you should use value you only have to check that variable's range and edit it accordingly. On the row tempsec = (mSecond + " "); you add a space.. mistake? Finally, you misspelled tempmin on the return row.
Good luck.
Note that your method has a value parameter. You should use this rather than directly access the fields in your class. Perhaps it might help for you to think about the purpose of the twoDigits() method. It seems to me that it is supposed to take an int value and pad it with a leading zero if the input is only a single digit. Note that my description in the previous sentence does not refer to the member variables that represent minutes and seconds; it only refers to the input value.

JAVA - While loop exiting when it shouldn't be?

ive been trying to fix this problem for myself for about 2 hours. I'm guessing someone is going to instantly spot out my problem. So my problem is that a while loop(or .equals is giving an incorrect result). Here's the code:
Integer i = 0;
while(!type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}
System.out.println(i + " type=" + type + " - questionType" + questionArray.get(i).questionType);
usedQuestionIndexes.add(i); //if question index has not been used - add it to used indexes
So the problem here is its exiting when the variable "type (string)" when it doesn't equal "questionArray.get(i).questionType (string)" which it shouldn't be. So lets say "type = 'hello'" and "questionArray.get(i).questionType = 'hi'" it is coming out of the loop?
The output from the code from the code above is this:
1 type=general - questionType=sport
So what is the problem here? Why is it saying the first condition is true when its not? the second condition is saying false(which is correct) heres the code for the method "hasQuestionBeenAsked":
public static Boolean hasQuestionBeenUsed(Integer questionIndex) {
for(Integer usedQuestionIndex : usedQuestionIndexes) {
if(questionIndex.equals(usedQuestionIndex)){
return true; //if index is found in usedQuestionIndexes array it will return that the index has been used
}
}
return false;
}
Thanks! If you need any extra info just tell me!
It's very simple - it's because you are negating the false by using the negation operator - (!). So even though you have false, you are ending up with true because (not) false = true. In your case, use
// Remove the negation - !
while(type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}

Extremely weird behaviour of return statement : Java

OK I have a weird problem. The code is as follows :
The method name is returnMultiPartHeading
if (recursionCount > 6 || i == list.size() - 1)
return -1;
multiPartHeading = multiPartHeading + " " + list.get(i + 1).getText();
Token token = new Token();
token.setText(multiPartHeading);
if (isHeadingType(token)) {
System.out.println("found " + multiPartHeading);
System.out.println("returning ...");
System.out.println("I is " + (i + 1));
return (i + 1);
} else {
returnMultiPartHeading(list, i + 1, multiPartHeading,
++recursionCount);
}
System.out.println("returning -1");
return -1;
}
The output is for a sample run is :
found xyz
returning...
I is 2
returning -1
why is this happening?? the if (isHeadingType(token)) evaluates to true , prints the two messages and then it totally skips the return i+1 and goes to return -1 instead. In the place I called it, I get -1 as the returned value instead of getting 2. Why is this happening?? Never saw this behaviour.
It's because in your else block, you don't actually return the result of the recursive call. You just call the method, ignore its result, and then fall through to the section below (with the return -1).
You need to change your else block to
else {
return returnMultiPartHeading(list, i + 1, multiPartHeading,
++recursionCount);
}
(assuming that your method really is called returnMultiPartHeading, which somehow doesn't sound right)
Looks like two calls are performed, the first wrote
found xyz
returning...
I is 2
and the second
returning -1
as it is a recursive method I think thats the reason
The if block is the second recursive call, which returns to the first recursive call, which was probably called by the else block. In the else block you do not return the value. Hence it skips out and returns -1.

How to check if a Float variable is negative in java

i am using the following code:
//Calculating Profit and Loss
float difference= sell_amount-buy_amount;
if (flag == 0) {
if ((difference<0)) {
System.out.print("Loss ");
System.out.println(difference - total_extra);
} else {
System.out.println("Profit ");
System.out.println(difference - total_extra);
}
}
even if in some inputs, the output is -0.53, it still says profit.. where am i going wrong
When you print out the difference, you also remove the value of total_extra.
Thus, let's say diffrence = 0.47 and total_extra = 1. The difference is indeed positive (thus printing "Profit", but when you print the value difference - total_extra, you print out "-0.53"

Categories

Resources