Wrong output in some tests - java

I have troubles in one method. In input we have string, for example (a+-b*i)some sign(c+-d*i). Program must calculate this and output result. I need to take index of sign in the first bracket and index in the second bracket. And than my program will be working. But, when in input (a-b*i)-(c-d*i) or (a-b*i)*(c-d*i) only, method returning wrong result -1.
My methods for two brackets.
public int getSign1(String str)
{
int sign1;
if(str.indexOf("+") < str.indexOf(")"))
sign1 = str.indexOf("+");
else if(str.indexOf("-", 2) < str.indexOf(")"))
sign1 = str.indexOf("-", 2);
else sign1 = -1;
return sign1;
}
public int getSign2(String str)
{
int sign2;
if(str.lastIndexOf("+") > str.lastIndexOf("("))
sign2 = str.lastIndexOf("+");
else if(str.lastIndexOf("-") > str.lastIndexOf("("))
sign2 = str.lastIndexOf("-");
else sign2 = -1;
return sign2;
}
The second method always working, but not the first (Please help me to find error).
Example: (1-2i)*(3-4i)
The first method is returning -1, but not 2. Why?

This happens because in the expression:
(1-2i)*(3-4i) you don't have any + char, and after seeing String#lastIndexOf:
the index of the last occurrence of the character in the character
sequence represented by this object, or -1 if the character does not
occur.
Then you know why str.lastIndexOf("+") will be -1. And it's of course < str.indexOf(")").
So sign1 will be -1.
You can fix it by:
if(str.indexOf("+")!= -1 && str.indexOf("+") < str.indexOf(")"))

For input (a-b*i)-(c-d*i) , here there is no '+' in this string.
public int getSign1(String str){
if(str.indexOf("+") < str.indexOf(")"))
sign1 = str.indexOf("+");
..
}
In this method first if you are checking '+' , hence it is not there its index is -1 which is less than str.indexOf(")") index so its returing -1.

Related

How does if condition finds unique letter in the string?

I am newbie here!!
I am unable to understand how "s.indexOf(s.charAt(i), s.indexOf(s.charAt(i)) + 1) == -1 "
checking for unique letter in the string. Below is the code,
String s = "leetcode";
for (int i = 0; i < s.length(); i++) {
if (s.indexOf(s.charAt(i), s.indexOf(s.charAt(i)) + 1) == -1) {
return i;
}
}
return -1;
Thank you for your help!
I am trying to find the unique character in the given string. I came across this code. I am trying to understand how it work!
For a rather verbose function like this, the best thing to do is break it down to the smallest possible computation (effectively).
Please refer to the following code snippet:
public class App {
private static int unique(String s) {
/** The String (non-primitive) is an array of chars (primitive).
* So, it'll be iterated with a loop. S.length () is the length of the char array.
*/
for (int i = 0; i < s.length(); i++) {
/** This will return the char element of the index i -> public char charAt(int index) */
char chatAtI = s.charAt(i);
/** Follow the println logs to see what's happening, or use a debugger on an IDE. */
System.out.println("chatAtI -> " + chatAtI);
/** Returns the index within this string of the first occurrence of the specified character
* or -1 if the character does not occur.
*/
int charIndex = s.indexOf(chatAtI) + 1;
System.out.println("charIndex -> " + charIndex);
/** The indexOf() method returns the position of the first occurrence of a specified character(s) in a string.
* It's an overloaded method.
* In the if condition, you're also using the variant which [1] returns the index of the first char occurrence
* and [2] start the search at the specified index or -1 if the character does not exist.
* The moment a unique occurrence is found, it'll return the index;
* meaning - "if the current char doesn't repeat in the char array, return its index and exit the method."
* Keep in mind the +1 above is what does the trick, as if that character doesn't repeat indexOf() returns -1.
*/
if (s.indexOf(chatAtI, charIndex) == -1) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
/** l is the first unique occurrence. Therefore, its index, 0, is returned. */
System.out.println(unique("leetcode"));
}
}
Articles for further reading:
https://www.digitalocean.com/community/tutorials/java-char-to-string-to-char-array
https://www.freecodecamp.org/news/charat-in-java-how-to-use-the-java-charat-method-2/
https://www.geeksforgeeks.org/java-string-indexof/
I hope this made sense. If not, let me know, as I can edit the answer and give more context.

What does this part in code mean? (Java)

Hey guys im new to java and i came across this thing
Ok so here i got something i just cant comprehend
here i have this class:
class FailSoftArray {
private int a[]; // reference to array
private int errval;
public int length;
public FailSoftArray(int size, int errv) {
a = new int[size];
errval = errv;
length = size;
}
public int get(int index) {
if(indexOK(index)) return a[index];
return errval;
}
public boolean put(int index, int val) {
if(indexOK(index)) {
a[index] = val;
return true;
}
return false;
}
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
What does indexOK(index) mean? What does it do?
This is a method to determine if the index its going to get in the array is valid.
Normally, if a value less than zero or greater than or equal to the length of the array was used as an index, it would cause an error, throwing an IndexOutOfBoundsException, since an array is indexed from 0 to length - 1.
The method avoids that possible outcome by ensuring the index will always be valid before using it, and it does this by comparing the index to see if it's >= 0, then comparing < length, then the & makes sure both are true (if both conditions are true, it can be used as an index to the array without throwing an exception.)
When you call indexOK, your program runs the following method, with an index as an argument:
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
indexOK returns a boolean value, so the result is either true or false. When is the result true?
if(index >= 0 & index < length) return true;
return false;
If the argument is larger than or equal to zero AND the argument is less than length, the result is true. Otherwise, the result is false.
The purpose of indexOK is to check whether or not a value is an appropriate index for an array. A negative index is invalid, as is an index which equals or exceeds the length of the array it references. So the check
index >= 0
determines whether or not the index is negative, and the check
index < length
determines whether or not the index equals or exceeds the length of the array it references.
Let me rewrite the method in a way that is more understandable:
private boolean indexOK(int index) {
if(index >= 0 & index < length) {
return true;
}
return false;
}
The method will return true, when the value of index is atleast 0 and smaller than length at the same time. You can use an if-statement without its curly brackets, but it will only use the following line as the 'inner block'. This is a rather bad practice, since it's a little unclear. Furthermore, it can be easily the cause of unwanted bugs and errors, since adding lines to the 'inner block' without adding curly brackets around them isn't that uncommon. In my humble opinion, 1 line (or 2 brackets) more of code isn't that much and one should always add them.

some weird stff im running into on java

So im working on java codingbat and this is the question:
Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string.
In other words, zero or more characters at the very begining of the given string, and at the very end of the string in reverse order (possibly overlapping).
For example:
the string "abXYZba" has the mirror end "ab". mirrorEnds("abXYZba") → "ab" mirrorEnds("abca") → "a" mirrorEnds("aba") → "aba" .
My code passed all the test except for the other test, which is not specified. I dont know what's wrong with it.
public String mirrorEnds(String string) {
String input = string, mirror = "";
int length = string.length();
for (int n = 0; n < (length+1) / 2; n++) {
if (input.charAt(n) != input.charAt(length - n - 1)) {
break;
}else if(length%2 == 1 && n == (length - 1)/2){
// System.out.println("length/2 = " );
return input;
}
else {
mirror += input.charAt(n);
}
}
return mirror;
}
You were correct in not needing to go though the entire word, but your logic is more complex than it needs to be, making it harder to find and fix the problem. The root cause of the test failure is in the last return statement. It must return string if the loop completes without breaking. You can fix your code by changing break; to return mirror; and changing the last return mirror; to return input;
The test that is failing is one like this:
mirrorEnds("abba") -> "abba"
A much simpler version of your code can be created like this:
public String mirrorEnds(String string) {
int len = string.length();
for (int i=0; i < len/2; ++i)
if (string.charAt(i) != string.charAt(len - 1 - i))
return string.substring(0, i);
return string;
}
mirrorEnds("abba")?
Anyways, I'm sure you could come up with a better question name than "some weird stuff"...
Since you are dividing n by 2 in your loop termination condition, it will end when halfway through the word. This is enough to tell the word is a palindrome, but not enough to build your output correctly. You have a condition handling palindrome with odd numbers of letter, but not even numbers of letters. I believe the failing test will be of the form "abba", where I believe what you have will return "ab", instead of "abba".
If you change you loop to:
for (int n = 0; n < length; n++) {
I believe it should be doing what you want. This also makes the short circuit case unnecessary, so:
for (int n = 0; n < length; n++) {
if (input.charAt(n) != input.charAt(length - n - 1)) {
break;
}
else {
mirror += input.charAt(n);
}
}
The first test I tried was with the string "abba" which fails. It returns ab, and not abba. As femtoRgon mentioned, you're not going through the entire word, which may some times be necessary. femtoRgon's solution works, as well as taking a slightly different approach to iterating through the word as follows:
public String mirrorEnds(String string) {
boolean matches = true;
StringBuilder mirrorEnd = new StringBuilder();
int index = 0;
while (matches && index < string.length()) {
if (string.charAt(index) == string.charAt(string.length() - index - 1))
mirrorEnd.append(string.charAt(index));
else
matches = false;
index++;
}
return mirrorEnd.toString();
}
public String mirrorEnds(String string) {
String comp="";
for(int i=0; i<string.length(); i++){
if(string.charAt(i)==string.charAt(string.length()-(i+1)))
comp= comp+ string.charAt(i);
else break;
}
return comp;
}

Comparing a character in Java

I'm having an issue comparing a character in Java. I'm trying to find a valid binary number, so I'm passing a string with the binary digits into a function and making sure they're either 0's or 1's. I loop through and check each character in the string, however, my function is telling me that it's bad (even when I know I've given it a proper binary number).
Here is the function:
public boolean isValidBinary(String s) {
//First we get the string length
int strLen = s.length();
//Now we loop through each character of the string
for(int x = 0; x < strLen; x++) {
//Assign the character to a variable each loopthrough
char c = s.charAt(x);
//Check if it's either a 0 or a 1
if(c != '0' || c != '1') {
return false;
}
}
//This is reached when all char's have been evaluated as 0 or 1
return true;
}
I have stared at this problem for quite some time and have been unable to figure it out, so any help would be appreciated.
That's a logical error. You meant && instead of ||.
You could use a regular expression for this anyway:
// must contain at least one digit, and only 0 or 1
public boolean isValidBinary(String s)
{
return s.matches("^[01]+$");
}
Rethink the logic in your inner condition: if(c != '0' || c != '1'). You want to use an AND here: if ((c != '0') && (c != '1')). This means that if both the conditions are true, then the input should be considered invalid, i.e,c is an invalid character if it isn't 0 and also isn't 1.
Consider the case where your code is checking a 1 character: it begins with the left side of the test: c != 0. This is true, and since the OR short-circuits, the result of your entire condition is true, and your function returns false, even though the current character being tested, 1, shouldn't invalidate the input.

Converting a character to an integer if the character is already a number in java

I'm trying to read a string's character to get the numeric value.
String cardNumber = in.next();
int currentIndex = cardNumber.length() - 1;
while (currentIndex >= 0)
{
int smallValue;
smallValue = Character.getNumericValue(currentIndex);
when smallValue runs, its not giving me the number. just a -1
You should be using Character.digit(), but you are calling it with the array index instead of the element value at that index.
You are passing currentIndex to Character.getNumericValue. I think you actually want to pass one of the characters of cardNumber.
I think this is what you want:
int currentIndex = cardNumber.length() - 1;
while (currentIndex >= 0)
{
int smallValue = Character.digit(cardNumber[i], 10);
}
Assuming cardNumber is a String, I believe this is what you want:
int smallValue = Character.digit(cardNumber.charAt(currentIndex), 10);

Categories

Resources