Hexadecimal Validation Algorithm - java

I'm trying to validate a hexadecimal number and its not going too well. I'm trying the code below but my logic isn't exactly on the ball. Any help?
if (!array[i].equals("A") || !array[i].equals("B") || !array[i].equals("C") || !array[i].equals("D") || !array[i].equals("E") || !array[i].equals("F"))
{
b[i] = false;
}
else
{
b[i] = true;
}
The aim of the above code is to give me a true or false value. True being the value is between A to F false being the value isn't between A to F.

if ((array[i]-'A') > 5)
b[i]=false;
else
b[i]=true;

Change all || to &&.
Right now your if condition always evaluates to true (since any string is not equal to either "A" or "B").
Alternatively, replace the whole construct with:
b[i] = array[i].equals("A") || array[i].equals("B") || array[i].equals("C") ||
array[i].equals("D") || array[i].equals("E") || array[i].equals("F");

if (array[i].equals("A") || array[i].equals("B") || array[i].equals("C") || array[i].equals("D") || array[i].equals("E") || array[i].equals("F"))
{ b[i] = true; }
else
{ b[i] = false; }
alternatively you could use a List and use .contains() as well.
List<String> hexchars = new ArrayList<String>();
hexchars.add("A");
hexchars.add("B");
hexchars.add("C");
hexchars.add("D");
hexchars.add("E");
hexchars.add("F");
return hexchars.contains("A");
But a regular expression would be the cleanest way to do this in the long run.

Related

JAVA: Putting alternative ( || ) in loop?

I have a quick question. I want to make my code shorter and I'm wondering whether I can put in some way below checkboxes into loop. The sense of this part of code is to enable "Find" button in case when at least one of checkbox is selected. Thank you in advance for every tip.
if (checkBoxes[0].isSelected() == true || checkBoxes[1].isSelected() == true
|| checkBoxes[2].isSelected() == true || checkBoxes[3].isSelected() == true || checkBoxes[4].isSelected() == true
|| checkBoxes[5].isSelected() == true || checkBoxes[6].isSelected() == true || checkBoxes[7].isSelected() == true
|| checkBoxes[8].isSelected() == true || checkBoxes[9].isSelected() == true || checkBoxes[10].isSelected() == true
|| checkBoxes[11].isSelected() == true || checkBoxes[12].isSelected() == true || checkBoxes[13].isSelected() == true
|| checkBoxes[14].isSelected() == true || checkBoxes[15].isSelected() == true || checkBoxes[16].isSelected() == true
|| checkBoxes[17].isSelected() == true || checkBoxes[18].isSelected() == true || checkBoxes[19].isSelected() == true
|| checkBoxes[20].isSelected() == true || checkBoxes[21].isSelected() == true) {
button.setEnabled(true);
Of course you can :
boolean found = false;
for (int i = 0; i < checkBoxes.length && !found; i++) {
found = checkBoxes[i].isSelected();
}
if (found) {
button.setEnabled(true);
}
or you can avoid the boolean variable and break out of the loop when you find the first selected checkbox :
for (int i = 0; i < checkBoxes.length; i++) { // you can also replace this with enhanced
// for loop
if (checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Why not to use stream?
if (Arrays.stream(checkBoxes).anyMatch(checkbox -> checkbox.isSelected())) {
button.setEnabled(true);
}
As you have an array of course you can use a loop.
Here is a version with an enhanced loop :
for (Checkbox checkBox : checkBoxes){
if (checkBox.isSelected()){
button.setEnabled(true);
break;
}
}
try this:
for(int i=0; i < checkBoxes.length; i++) {
if(checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Boolean j = false;
for (byte i = 0; i <= 21)
if (checkBoxes[i].isSelected() == true) {
j = true;
break;
if (j == true) {
//your code
}
you van use this code
it is so easy

The if statement is redundant in Java

I am getting a lightbulb on NetBeans saying "The if statement is redundant"
I want to know how these two are equal to one another
public boolean isVowel(char in)
{
char temp = Character.toLowerCase(in);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
{
return true;
}
else
{
return false;
}
}
and
public boolean isVowel(char in)
{
char temp = Character.toLowerCase(in);
return temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u';
}
I can see how it would return true if one of the vowels matches with temp. However, I am not seeing how it would return false. Would it simply just return false if none of the conditions are met?
Solved: I was looking at the problem the wrong way. For it to return false, each conditional statement would have to be false. Ideally it would return false if the return statement was equivalent to:
return false || false || false || false || false;
and true if any one condition is met
return false || false || false || false || true;
Thanks you guys, it really helped.
The two statements are identical.
int x = #; //user input
if (x==1) { //any condition resulting in a true or false
return true;
} else {
return false;
}
and
return (x==1); //same thing, returning true if true, false if false;
This expression:
(temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
calculates a boolean value. An if-statement tests this value. So instead of testing this expression in the ireturning the boolean value in the if/else-clause you can just return it.
Edit you can just prove if your char is a vowel?
Do it this way:
public boolean isVowel(char in) {
return "aeiou".indexOf(Character.toLowerCase(in)) < 0;
}
The two are indeed identical (and the if statement is redundant) and here's why.
The == is an equality operator, which means that, if the left side matches the right side, it evaluates to true, otherwise it evaluates to false. The || is a conditional operator, meaning that, if the equality on the left hand side evaluates to false, it will check the right side to see if it evaluates to true (or, if left side evaluates to true, then the expression will evaluate to true, called short-circuiting). If all of them evaluate to false, then the entire expression will evaluate to false.
Therefore, the if statement as you have it essentially turns into:
if(<expression>==true) { //in the case that the conditional evaluates to true
return true;
}
else { //in the case the conditional evaluates to false
return false;
}
So, that can just be reduced down to expression, since it will evaluate to a boolean anyways.
return <expression> //will be true if true, false if false
There's more on this in the Oracle documentation
boolean isNumeric(char cc){
//begin // test if cc is numeric
return (
(cc == '0')
| (cc == '1')
| (cc == '2')
| (cc == '3')
| (cc == '4')
| (cc == '5')
| (cc == '6')
| (cc == '7')
| (cc == '8')
| (cc == '9') );
} // isNumeric

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;
}
}

Cannot find symbol, Java and Strings

I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated!
public class PhoneNumber {
String phoneNumber;
public PhoneNumber(String num) {
phoneNumber = num;
}
public String decodePhoneNumber() {
// Takes string form phone number and decodes based on number pad
// Find code that makes if statement not care about caps
// so if a || b || c number[cnt] = 1 etc..
for (int cnt = 0; cnt < phoneNumber.length(); cnt++) {
char ch1 = phoneNumber.charAt(cnt);
if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) {
} else if (ch1.equalsIgnoreCase("d" || "e" || "f")) {
} else if (ch1.equalsIgnoreCase("j" || "k" || "l")) {
} else if (ch1.equalsIgnoreCase("m" || "n" || "o")) {
} else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) {
} else if (ch1.equalsIgnoreCase("t" || "u" || "v")) {
} else {
}
}
}
}
You have syntax errors and that is why you cannot find ch1.
Try modifying your code as per this syntax. These changes need to be done in all the conditionals.
if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison:
char ch1 = phoneNumber.toLowerCase().charAt(cnt);
if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') {
// Do something
}
...

Checking string for large amount of different, incremental values

Currently I am checking a string for the following:
if(parseCommand.contains("vlan1")
|| parseCommand.contains("Fa0/1i") || parseCommand.contains("Fa0/1o")
|| parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
|| parseCommand.contains("Fa1/11") || parseCommand.contains("Gi0"))
{
//do things here
}
However it may contain vlan1 up to vlan4094 and i have to check for these. What is the simplest way to do this, do I have to stick it all in a for loop incrementing to 4094 I guess?
for (int i = 1; i <= 4094; i++)
{
if(parseCommand.contains("vlan"[i]))
{
//do stuff here
}
}
if(other conditions from above)
{
//do same stuff again here
}
Or else I could stick all the conditions in the for loop and do everything inside there. This all seems messy, is there a non-messy way of doing it?
I think this regex should do it:
String parseCommand = "vlan4094";
if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" +
"[1-9][0-9]{0,2}|" +
"40(9[0-4]|[0-8][0-9])).*"))
System.out.println("matches");
[1-3][0-9]{3} - 1000-3999
[1-9][0-9]{0,2} - 1-999
9[0-4] - 90-94
[0-8][0-9] - 00-89
40(9[0-4]|[0-8][0-9]) - 4000-4094
Something like this is probably simpler:
String parseCommand = "vlan4094";
if (parseCommand.startsWith("vlan"))
{
int v = Integer.parseInt(parseCommand.substring(4));
if (v >= 1 && v <= 4094)
/* do stuff */
}
Suggested change:
Replace:
parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
with
parseCommand.matches(".*?Fa1/[0-9].*")
You can combie them into one boolean
boolean b = false;
for(int i = 1 ; i < 4094 ; i ++){
b = b || parseCommand.contains("vlan" + i);
}
Then check your boolean value
If the only problem is with "vlanXXX" you can remove the "vlan" part of the string:
parseCommand = parseCommand.replaceFirst("vlan", "");
and then cast it to int
int value = Integer.parseInt(parseCommand);
and then comparing this result with that whaat you want
if((value >= 1) && (value <= 4094)){....}
This will only work for the given case and you have to handle the case where parseCommand cannot be cast to int. And it is much more understandable than using whatever regular expresion

Categories

Resources