I am trying to create a method that will return true if the inputted integer has a one in it, and false if it does not. The method works correctly when the inputted number doesn't have a one or ends in a one. But if the one is not the last digit in the int, it incorrectly returns false. Any ideas whats wrong? Here is my script:
public static boolean hasOne(int n) {
boolean retval = false;
if (n % 10 == 1) {
retval = true;
} else {
dropLastDig(n);
}
return retval;
}
public static void dropLastDig(int input) {
int newNum = input/10;
if (newNum > 0) {
hasOne(newNum);
}
}
1000 should return true
211 should return true
1 should return true
3 should return false
234 should return false
You can use recursive function, it's faster:
public static boolean hasOne(int n) {
if(n<0) return hasOne(-n); // check for negatives
if(n==0) return false; // exit condition
if (n % 10 == 1) {
return true;
}
return hasOne(n/10);
}
Or cast it to String, and then check:
String.valueOf(n).contains("1");
Just use String.valueOf instead
return String.valueOf(x).contains("1");
try String.valueOf(n).contains("1")
Related
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;
Im currently working on a program to given integer input from user, print only those ones contain numbers 1 2 or 3. Here is my code so far:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int[] x=new int[5];
System.out.println("Enter 5 integers: ");
for(int i=0; i<x.length;i++) {
x[i]=s.nextInt();
boolean temp=recursion(x[i]);
if(temp==true) {
System.out.print(x[i]);
}
}
}
public static boolean recursion(int y) {
if(y%10==1 || y%10==2 || y%10==3) {
return true;
}
else if(y%10==0) {
return false;
}
else {
int remain=y/10;
recursion(remain);
}
}
So my approach is quite simple, I used a simple bool recursion to return true or false, true if it does contain 1 2 or 3 and false if not. The problem I am having is that I am not returning anything in my recursion else statement. I know I have to return something but not sure what to return or if its necessary. Anything I can change to make this work?
Your base cases for recursion are a little off, so in the statement
else if(y%10==0), the number 100 would cause this to fail even though it is valid. you want your false base case to actually be else if (y == 0) which means you have gone through the entire number. the solution looks like:
public static boolean recursion(int y) {
int positive = Math.abs(y);
if(positive%10==1 || positive%10==2 || positive%10==3) {
return true;
} else if (positive == 0) {
return false;
}
return recursion(positive / 10);
}
edit: Calling absolute value on the number makes it work for negative numbers as well, but you can call abs on the integer being passed in to the same effect.
I think you just have to do
return recursion(remain);
Use below code, hope this will help.
public static boolean recursion(int y) {
if(y%10==1 || y%10==2 || y%10==3) {
return true;
}
else if(y%10==0) {
return false;
}
else {
int remain=y/10;
return recursion(remain);
}
}
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).
Given three numbers as input, return true if at least one of them is a prime number. For solving this problem, define a function that checks whether a number is a prime or not and use that function
MyApproach:
I made a function that checks first whether the num is prime or not(CHECK PRIME).After checking the 3 numbers,if in that function any of the number is prime it should return true
otherwise false.
But I am getting wrong Ans for the test case
Below is my Code:
public boolean anyonePrime(int num1, int num2, int num3)
{
boolean b1=checkPrime(num1);
boolean b2=checkPrime(num2);
boolean b3=checkPrime(num3);
if((b1==true) ||(b2==true) ||(b3==true)) //#Edit
return true;
else
return false;
}
public boolean checkPrime(int num)
{
boolean b0=true;
if(num==1)
return false; //#Edit
else
{
for(int i=2; i<=num/2; i++)
{
if(num % i==0)
{
return false; //#Edit
}
}
return true;
}
if(b0==true)
return true;
else
return false;
//write your code here
}
}
# Edit passes all test cases
For the Input
Parameters ActualOutput Expected Output
'169' '361' '529' true false
The main issue is that b0=true always. But..
it is also rather inefficient as you don't stop immediately if the first one is prime,
nor do you stop immediately if there is a divisor,
nor do you stop when you reach the square root of num
also b3=true which should be b3==true.
You appear to have a typo in your code. You set b0=true; before checking if(b0==true);, so it will always return true. The simple thing to do would simply be to return false as soon as any check finds it is not prime, rather than setting b0 to false and then continuing to do more work.
Try this:
public boolean anyonePrime(int num1, int num2, int num3)
{
return (checkPrime(num1) || checkPrime(num2) || checkPrime(num3))
}
public boolean checkPrime(int num)
{
boolean b0=true;
if(num==1)
b0=false;
else
{
for(int i=2; i<=num/2; i++)
{
if(num % i == 0)
{
b0=false;
}
}
}
if(b0==true)
return true;
else
return false;
//write your code here
}
}
I just removed the 'b0 = true line' and tidied up some code
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);
}