Combine 2 Boolean statements to make another one - java

I am trying to combine two boolean statements in order to validate a number.
This is the code for the two functions:
public boolean numberOne(String number)
{
int a = Integer.parseInt(number);
if(a >= 0 && a <= 7 && number.length() <= 1) {
return true;
}
else {
return false;
}
}
public boolean numberTwo(String number)
{
int b = Integer.parseInt(number);
if(b >= 01 && b <= 15 && number.length() <= 2) {
return true;
}
else {
return false;
}
}
Now I want to create another Boolean function to validate this number when both combined e.g. 215 would be true and 645 would be false.
How can I do this?
Thanks

Two changes. The first is a side note. This code
if (long_test) {
return true;
} else {
return false;
}
should be rewritten as this:
return long_test;
The other change described by dampee once he gets his variable names to match.

Ok. So you want to split the string and have the first number of the string compared to the first function and the last two numbers compared to the second function?
public boolean numberThree (String number) {
String part1 = number.substring(0, 1);
String part2 = number.substring(1);
return numberOne(part1) && numberTwo(part2);
}

Related

How to use a "Do While" loop to iterate through a list

public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
(JAVA only)
P.s This is a function i have tried, in order to check the first argument, and if it contains a number that is larger than the second argument, it will then return true, and flase otherwise.
Note that it is using do while loop. I just don't know which part of this code i have done wrong, because the system keeps telling me that "java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0".
Thank u, any hint will be much appriciated.
your list of Integers is empty. you can't access an index of an empty list:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
if (numbers.isEmpty()) return false;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
A do-while control block works as follows:
Execute the do block
Check the condition. If it holds, return to (1)
Notice the order of this flow. Unlike a standard while, do-while will always execute one iteration before checking the condition. Therefore, for an empty list you will always try to access the 0-index element of the table, which does not exist, hence the error. You can use a while loop to avoid this:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
while (d < numbers.size()) {
if (numbers.get(d) > number){
return true;
}
d++;
}
return false;
}
You should check whether the collection is empty
like this
if(numbers == null || numbers.isEmpty()) {
return false;
}
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;

Method to Check Password in Java Not Working

I'm trying to write a method that returns if the string is or isn't a valid password in CodeHS.
It needs to be at least eight characters long and can only have letters and digits.
In the grader, it passes every test except for passwordCheck("codingisawesome") and passwordCheck("QWERTYUIOP").
Here's what I have so far:
public boolean passwordCheck(String password)
{
if (password.length() < 8)
{
return false;
}
else
{
char c;
int count = 0;
for (int i = 0; i < password.length(); i++)
{
c = password.charAt(i);
if (!Character.isLetterOrDigit(c))
{
return false;
} else if (Character.isDigit(c))
{
count++;
}
}
if (count < 2)
{
return false;
}
}
return true;
}
If anyone can help, I'd appreciate it. Thanks.
Try an approach using patterns (this is simpler than looping):
public boolean passwordCheck(String password)
{
return password!=null && password.length()>=8 && password.matches("[A-Za-z0-9]*");
}
Decent tutorial on regular expressions (that's where the A-Z magic comes from): http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Assuming your requirement is as stated
It needs to be at least eight characters long and can only have letters and digits
Then there is no need to count digits. Simply check that the password is the minimum length, then loop over every character returning false if any are not a letter or digit. Like,
public boolean passwordCheck(String password) {
if (password != null && password.length() >= 8) {
for (char ch : password.toCharArray()) {
if (!Character.isLetterOrDigit(ch)) {
return false;
}
}
return true;
}
return false;
}
It's failing those tests because your code checks that the password must have at least 2 digits:-
if (count < 2)
{
return false;
}
And your test strings don't have any. Remove this piece of code and it should work. For a better way of doing it, see other answers.

To check if string is palindrome using recursion?

There is something wrong with my code as one the testcase in my assignment is coming out wrong, giving me runtime error when I submit the code online. That testcase could be any String. I believe that everything is fine with the code as I have checked it manually for many testcases.
HERE IS THE CODE
public static boolean isStringPalindrome(String input) {
if(input.length()==0 || input.length()==1)
return true;
int first = 0;
int last = input.length()-1;
if(input.charAt(first) != input.charAt(last))
return false;
String str="";
for(int i=first+1;i<last;i++){
str = str+input.charAt(i);
}
boolean sa = isStringPalindrome(str);
return sa;
}
Sample Input
racecar
Output
true
Sample Input
pablo
Output
false
Your code appears to be overly complicated for recursively testing if the String is a palindrome. Something like,
public static boolean isStringPalindrome(String input) {
if (input == null) {
return false;
} else if (input.isEmpty() || input.length() == 1) {
return true;
}
int len = input.length() - 1;
return input.charAt(0) == input.charAt(len) //
&& isStringPalindrome(input.substring(1, len));
}
Is recursive without embedding a for loop. Because if you can do that, you should do something like
public static boolean isStringPalindrome(String input) {
if (input == null) {
return false;
} else if (input.isEmpty() || input.length() == 1) {
return true;
}
int len = input.length();
for (int i = 0; i <= len / 2; i++) {
if (input.charAt(i) != input.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
A simpler way to check for palindrome can be:
public static boolean isPalindrome(String s)
{ if (input == null)
return false;
else if(s.length() == 0 || s.length() == 1)
return true;
/* check for first and last char of String:
* if they are same then do the same thing for a substring
* with first and last char removed. and carry on this
* until you string completes or condition fails.
*/
if(s.charAt(0) == s.charAt(s.length()-1))
return isPalindrome(s.substring(1, s.length()-1));
return false;
}
Update
You are getting runtime error(NZEC) which means non-zero exit code. It means your program is ending unexpectedly. I don't see any reason except that your program doesn't have a null check. Otherwise, I have gone through your code carefully, you are doing the same thing which I have suggested.

Return multiple values from void and boolean methods

I have the following problem: Having a boolean static method that computes similarity between two integers, I am asked to return 4 results:
without changing the return type of the method, it
should stay boolean.
without updating/using the values of external variables and objects
This is what I've done so far (I can't change return value from boolean to something else, such as an int, I must only use boolean):
public static boolean isSimilar(int a, int b) {
int abs=Math.abs(a-b);
if (abs==0) {
return true;
} else if (abs>10) {
return false;
} else if (abs<=5){
//MUST return something else, ie. semi-true
} else {
//MUST return something else, ie. semi-false
}
}
The following is bad practice anyway, but If you can try-catch exceptions you can actually define some extra outputs by convention. For instance:
public static boolean isSimilar(int a, int b) {
int abs = Math.abs(a-b);
if (abs == 0) {
return true;
} else if (abs > 10) {
return false;
} else if (abs <= 5){
int c = a/0; //ArithmeticException: / by zero (your semi-true)
return true;
} else {
Integer d = null;
d.intValue(); //NullPointer Exception (your semi-false)
return false;
}
}
A boolean can have two values (true or false). Period. So if you can't change the return type or any variables outside (which would be bad practice anyway), it's not possible to do what you want.
Does adding a parameter to the function violate rule 2? If not, this might be a possible solution:
public static boolean isSimilar(int a, int b, int condition) {
int abs = Math.abs(a - b);
switch (condition) {
case 1:
if (abs == 0) {
return true; // true
}
case 2:
if (abs > 10) {
return true; // false
}
case 3:
if (abs <= 5 && abs != 0) {
return true; // semi-true
}
case 4:
if (abs > 5 && abs <= 10) {
return true; // semi-false
}
default:
return false;
}
}
By calling the function 4 times (using condition = 1, 2, 3 and 4), we can check for the 4 results (only one would return true, other 3 would return false).

Check first two digit number lies between 00 && 99

I develop a function that reject number starting with 00 and 99.
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
if (number.charAt(0)==00){
}
return false;
}
How can i implement this function properly.
that if statement will always returns false.
One solution:
if (number.trim().startsWith("00") || number.trim().startsWith("99")){
System.out.println("not valid");
}
Use .startsWith():
if (number.startsWith("00") || number.startsWith("99")) ...
.charAt() returns a single character, not a string.
(out of sheer curiosity, why this? code_postal.getText().toString(); From the name of .getText(), you'd have figured out that it already returned a String... Bah.)
EDIT So, on demand, another version which checks by converting to an int first...
final int begin = Integer.parseInt(number.subString(0, 2));
if (begin % 99 == 0) // can only be true if number is 0 or 99
// etc
If I understand your question specially heading "lies between 00 && 99" you want this
try
{
String s = "45Abc";
Integer i = Integer.parseInt(s.substring(0,2));
if (i>00 && i<99)
System.out.println("True");
}catch (NumberFormatException e)
{
// TODO Auto-generated catch block
System.out.println("First two characters are not numbers");
}
Use your logic look like below
private boolean isValid(String str) {
if (str == null)
return false;
String tempStr = null;
try {
if (str.length() > 2) {
tempStr = str.substring(0, 2);
} else {
tempStr = str;
}
int number = Integer.parseInt(tempStr);
if (number >= 0 && number <= 99) {
return false; //in between 0 to 99
} else {
return true;
}
} catch (NumberFormatException e) {
}
return false;
}
You can use String class indexOf() method :
if (number.indexOf("00")==0 || number.indexOf("99")==0)
EDITED: - You need this as I understood from your question subject line "Check first two digit number lies between 00 && 99".
public static boolean isValid(String name) {
boolean isValid = true;
if(name.length()>2){
name = name.substring(0, 2);
}
try {
int number = Integer.parseInt(name);
if(number>-1 || number<100){
isValid = false;
}
}
catch(Exception e){
isValid = false;
}
return isValid;
}
To check if the Entered number starts with "00" or "99"
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
if(number.startsWith("00") || number.startsWith("99")){
return true;
}
return false;
}
To check if the Entered number is between "00" and "99"
public Boolean valideCode(EditText code_postal){
String number = code_postal.getText().toString();
String firstTwoDigits = number.substring(0,2);
if (Integer.valueOf(firstTwoDigits )>=0 && Integer.valueOf(firstTwoDigits )<=99){
return true;
}
return false;
}
Note: The title of your question and description are different. hence two answers.
Just to be different (and inefficient and impenetrable):
return !number.matches("^\s?(00|99).+");

Categories

Resources