Method always returns true? - java

I have a method that is being called to validate that an IP address is assignable. No matter what I pass to it, it is always returning true. What do I need to set the return as to get this method working properly?
public boolean checkValidIPClass(String x) {
for (int i = 0; i < 4; i++) {
try {
if (retString.equals("A")) {
if ((intParts[1] == 0) && (intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[1] == 255) && (intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("B")) {
if ((intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("C")) {
if (intParts[3] == 0)
return false;
if (intParts[3] == 255)
return false;
}
} //ends try
catch (NumberFormatException nfe) {
return false;
} //ends catch
} //ends for
return true;
}
retString is making it to the method and is a string that was returned from another method that checks what class the IP address is and assigns it, this was verified with a print statement. Thanks!
EDIT: How has this been answered and downvoted? My question wasn't about comparing the strings, it was about the method always returning true even when I know the if statements should be catching the error and returning false?
EDIT2: Updated my code.

I don't get why you're doing a loop, but you could try this:
public boolean checkValidIPClass(String ipClass, String ipAddress)
{
if (ipClass.contentEquals("A"))
{
if (ipAddress.endsWith("0.0.0") || ipAddress.endsWith("255.255.255"))
return false;
}
else if (ipClass.contentEquals("B"))
{
if (ipAddress.endsWith("0.0") || ipAddress.endsWith("255.255"))
return false;
}
else if (ipClass.contentEquals("C"))
{
if (ipAddress.endsWith("0") || ipAddress.endsWith("255"))
return false;
}
return true;
}
Since you're just checking the ending array parts of the IP address, you don't need to break it into an array, just leave it as a string.
And keep in mind that this would only satisfy IPv4 formatted IP addresses. It will not work for IPv6 formatted addresses

Related

How to compare two 2D Arrays in Java?

I am a beginner trying to write a function in Java that returns true if two passed 2D arrays of int type are the same size in every dimension, and false otherwise. Requirements are that if both arrays are null you should return true. If one is null and the other is not you should return false.
Somehow getting an error for my code:
public static boolean arraySameSize(int[][] a, int[][] b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.length == b.length) {
for (int i = 0; i < a.length; i++) {
if (a[i].length == b[i].length) {
return true;
}
}
}
return false;
}
Any help would be appreciated!
Edit: Problem is "Runtime Error: null"
Your logic looks almost spot-on already. The only issue I see is in the logic handling the case where both arrays are not null and have the same first dimension. You should be returning false if any index does not have matching lengths:
public static boolean arraySameSize(int[][] a, int[][] b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (a.length != b.length) {
return false;
}
// if the code reaches this point, it means that both arrays are not
// null AND both have the same length in the first dimension
for (int i=0; i < a.length; i++) {
if (a[i] == null && b[i] == null) {
continue;
}
if (a[i] == null || b[i] == null) {
return false;
}
if (a[i].length != b[i].length) {
return false;
}
}
return true;
}
Follow the demo link below to see some of examples of this method working correctly.
Demo

Why is my code returning true for cases that should return false? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 6 years ago.
I am writing a code that will import a string of characters from a text file, analyze the string using a stack and determine which "language" the string belongs to based on whether or not it fits certain rules. The code below tests to see if an input follows the pattern (A^nB^)^p (where n is greater than or equal to 0). The way I have it written is to load the first set of A's and B's onto a stack, then load the second set of A's and B's onto another stack, pop the two stacks at the same time and compare the returned values. If they match, move on (until the two stacks empty at the same time, hopefully) if they don't then return false.
public static boolean checkL4(File file) throws IOException
{
Stack stack1 = new Stack();
Stack stack2 = new Stack();
Stack stack3 = new Stack();
boolean firstCompare = true;
boolean bStart = false;
char w = 0;
try (Scanner sc = new Scanner(file).useDelimiter("\\s*"))
{
while (sc.hasNext()){
w = sc.next().charAt(0);
if (w == 0) {
return true;
}
if (w != 'A' && w != 'B')
{
return false;
}
if (w == 'A') {
if(!bStart) {
stack1.push(w);
stack3.push(w);
}
if(bStart && stack2.isEmpty()) {
stack2.push(w);
} else {
if (firstCompare) {
while (!stack1.isEmpty() || !stack2.isEmpty()) {
if (!stack1.isEmpty() && stack2.isEmpty())
{
return true;
}
if (stack1.isEmpty() && !stack2.isEmpty()) {
return false;
} else {
if (stack1.pop() == stack2.pop()) {
return true;
} else {
return false;
}
}
}
stack1.push(w);
firstCompare = false;
} else {
if(stack1.isEmpty()){
while (!stack3.isEmpty() || !stack2.isEmpty()) {
if (stack3.isEmpty() && !stack2.isEmpty()) {
return false;
} else {
if (stack2.isEmpty() && !stack3.isEmpty()) {
return false;
} else {
if (stack3.pop() == stack2.pop()) {
return true;
} else {
return false;
}
}
}
}
stack1.push(w);
}
if (stack3.isEmpty()){
while (!stack1.isEmpty() || !stack2.isEmpty()) {
if (stack1.isEmpty() && !stack2.isEmpty()) {
return false;
} else {
if (stack2.isEmpty() && !stack1.isEmpty()) {
return false;
} else {
if (stack1.pop() == stack2.pop()) {
return true;
} else {
return false;
}
}
}
}
stack1.push(w);
}
}
}
}
if (w == 'B') {
bStart = true;
if(bStart && stack2.isEmpty()) {
stack2.push(w);
}
if(bStart && !stack2.isEmpty()) {
if (!stack1.isEmpty()) {
stack3.push(w);
}
if(!stack3.isEmpty()) {
stack1.push(w);
}
}
}
}
}
return false;
}
This code works correctly for most inputs (returning true for AB and AABBBAABBB, and returning false for BBAA) but in some cases where it should return false (like ABBA and AABBCCD) it returns true. So why is it returning true for cases that are palindromes and cases where there are non A and non B letters. I know I have a statement in there that states if w (the input) is not and A and not a B, return false. This is worked in similar methods I have written, so why not this one? I have also written this to return false if the two returned values don't match (which they shouldn't if the input is a palindrome).
I think you should use .isEqual to compare between two Strings instead of using ==

Can't figure out how to fix my code

Hi for the past few hours i have been trying to fix my code. The problem is that when I go to check if "" is an integer is returns true when it should be false. I know why this is happening, it is because it doesn't enter the for loop and returns true , but I can't seem to figure out how to make it return false for "". I can provide more info if needed.
public boolean isInteger(String str)
{
for (int x = 0, n = str.length(); x < n; x++)
{
char c = str.charAt(x);
if (c < '0' || c > '9')
{
if (c != 0 || c != '-')
{
return false;
}
}
}
return true;
}
Thank you for spending your time on trying to help me :)
You could check valid input (ie, a string with length = 0) and return false before you ever try the loop. You're correct, though, it's not entering the loop and just returning true.
--edit--
Something like
if (string == null) || (string.length() == 0){
return false
}
In your algorithm, an empty string will always return true. You just need to add a check:
if(str==null || str.length()==0) return false;
Alternatively, you can use this function:
public static boolean isInteger(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}

Java nested ifs

Below is a small function which when given two numbers (a, b), returns true if one of the numbers is a teen-number. Returns false if both are teen. Returns false if both are not teen. I failed these test cases but I can't figure out why. Help?
(13, 99), (14, 20), and (16, 9)
public boolean loneTeen(int a, int b)
{
if(a<=19 && a>=13)
{
if(b<=19 && b>=13)
{
return false;
}
}
else if(a<=19 && a>=13)
{
return true;
}
else if(b<=19 && b>=13)
{
return true;
}
return false;
}
All three test cases will enter first if branch, they will not match inner condition and, since they already matched first branch, will not match any of else if's. So, they will all return false which is wrong.
Using a small auxiliary method can make your life much easier (and the code more readable!):
private boolean isTeen(int a) {
return a > 12 && a < 20;
}
public boolean loneTeen(int a, int b) {
if(isTeen(a) && isTeen(b) ||
!isTeen(a) && !isTeen(b)) {
return false;
}
return true;
}
First else won't be executed as you are putting the same condition on both if and else.try putting
if( a>=13 && a<=19 && b>=13 && b<=19){return false;}
else if(a>=13 && a<= 19){return true;}
else if(b<=19 && b>=13){return true;}
else return false;

Inversion of return value

I have a flag that I want to pass to a function which returns true or false based on a value in a map:
// userList is a List<String> and is stored as the value field in a map
// user is a String
if(flag)
{
if (userList == null)
return false;
else if(userList.size() == 0)
return true;
return userList.contains(user);
}
else
{
if (userList == null)
return true;
else if(userList.size() == 0)
return false;
return !userList.contains(user);
}
My question is this: is there anyway to tidy this code up, there is a lot of replication (the if and else block are identical, except their return values are the opposite of each other).
I'm not a very experienced code, and I'd really appreciate some guidance!
Use the flag value instead of constants.
if (userList == null)
return !flag;
else if(userList.size() == 0)
return flag;
A XOR will serve for the last statement (left as exercise to the reader :-p)
We can move the common processing to its own method, then branch based on the flag variable as follows.
public boolean userExists(String user) {
return userList != null && (userList.size() == 0 || userList.contains(user));
}
...
if(flag) return userExists(user);
else return !userExists(user);
As a side note, you may have a logic error. I'm not sure why you'd want to return true in the case of userList.size() == 0.
Here's a way to simplify the whole snippet of code, removing the outer if/else statement:
if (userList == null)
return !flag;
else if (userList.isEmpty())
return flag;
return userList.contains(user) == flag;
if (userList == null)
return !flag;
else if(userList.size() == 0)
return flag;
return flag ? userList.contains(user) : !userList.contains(user);ยท
You can easily remove duplication by making the return value be a function of flag :
if (userList == null) {
return !flag;
} else if (userList.size() == 0) {
return flag;
}
return !flag ^ userList.contains(user);
return userList != null && userList.contains(user) == flag;
Might do the job.

Categories

Resources