return statement in boolean method - java

I do not understand what I should return. My method returns false if the last time it goes
through the for-loop it is false. If the last time is true than it returns true. But I want it to return false regardless of where the false occurred.
public class test {
public static void main(String[] args) {
int number = 4;
int[] intArray = {4, 8, 12, 16};
System.out.println(allMultipleOf(intArray, number));
}
public static boolean allMultipleOf(int[] ary, int n){
boolean a = true;
for(int i = 0; i < ary.length; i++){
if(ary[i] % n == 0){
a = true;
//System.out.println(a);
break;
} else {
a = false;
}
}
}
return a; //what should I return
}

You can return false early from the method, if we reached the end without returning false, then return true:
public static boolean allMultipleOf(int[] ary, int n) {
for (int i = 0; i < ary.length; i++) {
if (ary[i] % n != 0) {
return false;
}
}
return true;
}

It should return false, the default of the boolean is print at this place.
You can make the return statement within the method. it return true.
public static boolean allMultipleOf(int[] ary, int n) {
boolean a = true;
for(int i = 0; i < ary.length; i++) {
if (ary[i] % n == 0) {
a = true;
//System.out.println(a);
break;
} else {
a = false;
}
}
return a;
}

Related

Boolean To Return True or False in Method

Cannot figure out how to code my method, anything I try gives me compile errors. In short I need my method to iterate through my passed down boolean array. Find out if False appears consecutively more or if True appears consecutively more. In the array I provided False appears more consectively, thus it should return false back to main. I'm at a total loss right now any tips?
public class booleanTF
{
public static void main(String [] args)
{
boolean[] guess = {false,true,false,false,false,true,true};
}
public static boolean longerTF(boolean[] guess)
{
int variable = 0;
for(int x = 0; x < guess.length; x++)
{
if(guess[x]
}
}
You can use flags to check if the current element is true or false and what was the previous element of the array.
You can try the following approach. Ask me if you have any doubts
public class booleanTF {
public static void main(String[] args) {
boolean[] guess = { false, true, false, false, false, true, true };
boolean result = longerTF(guess);
System.out.println(result);
}
public static boolean longerTF(boolean[] guess) {
int variable = 0;
boolean trueFlag = false;
boolean falseFlag = false;
int trueCount = 0, falseCount = 0;
for (int x = 0; x < guess.length; x++) {
if (guess[x] == true) {
if (falseFlag == true) {
trueCount = 0;
}
trueFlag = true;
falseFlag=false;
trueCount++;
} else {
if (trueFlag == true) {
falseCount = 0;
}
falseFlag = true;
trueFlag=false;
falseCount++;
}
}
if (trueCount > falseCount) {
return true;
} else {
return false;
}
}
}
Obviously not the most effective way to do this, but:
public static boolean longerTF(boolean[] guess) {
return findMaxSeqLength(guess, true) > findMaxSeqLength(guess, false);
}
private static int findMaxSeqLength(boolean[] array, boolean value) {
int maxSeqLength = 0;
int counter = 0;
for (boolean b : array) {
counter = (b == value) ? ++counter : 0;
maxSeqLength = Math.max(maxSeqLength, counter);
}
return maxSeqLength;
}
Find the longest true sequence, find the longest false sequence and compare their lengths.
public static void booleanTF(){
boolean[] arr = {true,true,false,false,false};
int fIndex = 0;
int fMaxCount = 0;
int tIndex = 0;
int tMaxCount = 0;
for(boolean ar : arr){
if(ar){
tIndex++;
if(tIndex > tMaxCount){
tMaxCount = tIndex;
}
fIndex= 0;
}else{
fIndex++;
if(fIndex > fMaxCount){
fMaxCount = fIndex;
}
tIndex=0;
}
}
if(fMaxCount > tMaxCount){
System.out.println("False appers more " + fMaxCount);
}else if (tMaxCount > fMaxCount){
System.out.println("True appers more " + tMaxCount);
}else{
System.out.println("Same Count " + tMaxCount);
}
}

Check input string to int

I have this method:
public static int parseInt(String str) {
if (isValidNumber(str)) {
int sum = 0;
int position = 1;
for (int i = str.length() - 1; i >= 0; i--) {
int number = str.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
return sum;
}
return -1;
}
which converts a string into a integer. And as you can see it is (at the moment) in a if-statement with a method which checks if the input is a valid input for my purpose:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(c >= '0' && c <= '9'){
return true;
}
}
return false;
}
I want the string to be number only (negative and positive) no other is allowed. At that time a string i.e 1a1a will be converted to a integer which it shouldn't whereas -1 will not be converted. I think you guys understand what I mean. I don't know how to do that.
Please help!
Try this:
CODE:
public class validNumbers {
public static void main(String[] args) {
System.out.println(parseInt("345"));
System.out.println(parseInt("-345"));
System.out.println(parseInt("a-345"));
System.out.println(parseInt("1a5b"));
}
public static int parseInt(String str) {
String numberWithoutSign = removeSign(str);
if (isValidNumber(numberWithoutSign)) {
int sum = 0;
int position = 1;
for (int i = numberWithoutSign.length() - 1; i >= 0; i--) {
int number = numberWithoutSign.charAt(i) - '0';
sum += number * position;
position = position * 10;
}
if(isNegative(str)){
return -(sum);
}else{
return sum;
}
}
return -1;
}
/**
* Removes sign in number if exists
*/
public static String removeSign(String number){
if(number.charAt(0) == '+' || number.charAt(0) == '-'){
return number.substring(1);
}else{
return number;
}
}
/**
* Determines if a number is valid
*/
public static boolean isValidNumber(String number) {
for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);
if(c >= '0' && c <= '9'){
continue;
}else{
return false;
}
}
return true;
}
/**
* Determines if a number is negative or not
*/
public static boolean isNegative(String number){
if(number.charAt(0) == '-'){
return true;
}else{
return false;
}
}
}
OUTPUT:
345
-345
-1
-1
To check if a string is a real number you can use a method like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
The problem is with your function isValidNumber. It should return a false on first occurrence of a non numeric value, as follows:
public static boolean isValidNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if(!(c >= '0' && c <= '9')){
if (i > 0) {
return false;
}
//This will only be invoked when `i == 0` (or less, which is impossible in this for loop), so I don't need to explicitly specify it here, as I have checked for `i > 0` in the above code...
if (c != '-' && c != '+') {
return false;
}
}
}
return true;
}

Java Program: return statements not working

This program creates various methods for a class and runs each method. When I run the methods, the return statements do not work in the methods, although the integer value entered is definitely passed to the object (I tested with a print statement). I am sure the issue is somewhere with my static declarations.
can anyone help?
import java.util.Scanner;
public class MyInteger {
public static int storedValue;
public int value;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Class with various methods test. Please enter an integer:");
int num = input.nextInt();
MyInteger x = new MyInteger(num);
storedValue = x.value;
System.out.println("Now performing returnInt");
x.returnInt();
System.out.println("Now performing isEven");
x.isEven();
}
MyInteger(int a){
value = a;
}
public int returnInt(){
return storedValue;
}
public boolean isEven(){
if(value % 2 == 0){
return true;
}
else{
return false;
}
}
public boolean isOdd(){
if(value % 2 != 0){
return true;
}
else{
return false;
}
}
public boolean isPrime(){
if (value == 2){
return true;
}
for (int i = 2; i < value;i++){
if (value % i == 0){
return false;
}
}
return true;
}
public boolean isEven(int a){
if (a % 2 == 0){
return true;
}
else{
return false;
}
}
public boolean isOdd(int a){
if (a % 2 != 0){
return true;
}
else{
return false;
}
}
public boolean isPrime(int a){
if (a == 2){
return true;
}
for (int i = 2; i < a;i++){
if (a % i == 0){
return false;
}
}
return true;
}
public boolean isEven(MyInteger a){
if (a.value % 2 == 0){
return true;
}
else{
return false;
}
}
public boolean isOdd(MyInteger a){
if (a.value % 2 != 0){
return true;
}
else{
return false;
}
}
public boolean isPrime(MyInteger a){
if (a.value == 2){
return true;
}
for (int i = 2; i < a.value;i++){
if (a.value % i == 0){
return false;
}
}
return true;
}
public boolean equals(int a){
if (value == a){
return true;
}
else{
return false;
}
}
public boolean equals(MyInteger a){
if (value == a.value){
return true;
}
else{
return false;
}
}
public int parseInt(String s, int radix){
for (int i = (s.length()-1); i >= 0; i--){
radix += (int)s.charAt(i)*(Math.pow(10, i));
}
return radix;
}
}
First, remove the static storedvalue.
// public static int storedValue;
Then change your returnInt to return the value. Like,
public int returnInt(){
return value;
}
Finally, assign the return(ed) value in your caller (main, or use it directly). Something like
System.out.println("Now performing returnInt");
int v = x.returnInt();
System.out.printf("Value = %d%n", v);
System.out.println("Now performing isEven");
if (x.isEven()) {
System.out.println("It's even");
} else {
System.out.println("It's odd");
}

How do I make this output a boolean?

So here's my code, I want the output to be like this:
Given two numbers, is the second input a multiple of the first?
For Example:
Input:
3
6
Output:
true
public boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
When I try it I get an error, I think it's because the return statement is within the if and else statements.
The code is perfectly fine .. Error must be Somewhere else
public class Test1 {
public static void main(String[] args) {
System.out.println(multiple(3, 9));
}
public static boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
}
Output
true
here is output see IDEONE
The easiest way is to return the result of your if statement.
return n % m == 0;
I'm not sure what i/j are doing. You don't use them except to increment, but they are local to the function and get GC'd after the return. What you have now is basically this:
boolean bool = some_calculation();
if (bool == true)
{
return true;
}
else
{
return false;
}

boolean allLess(int[] one,int[] two) method

so I am trying to make this method that takes in two int Arrays and returns true if each element in the first array is less than the element at the same index in the second array if the arrays are of different lengths then it will compare up to the length of the shorter array. this is what i have so far but i keep failing two j unit tests and cant figure out what is causing it. Thank you for any help in advance.
here are the two junit tests i am failing
#Test
public void testSecondLessFirstLonger() {
int[] one = { 5, 5, 5 };
int[] two = { 4 };
boolean actual = Program1.allLess( one, two );
assertFalse( "Incorrect result",actual );
}
#Test
public void testSecondLessSecondLonger() {
int[] one = { 2 };
int[] two = { 1, 0 };
boolean actual = Program1.allLess( one, two );
assertFalse( "Incorrect result",actual );
}
import java.util.Arrays;
here is the code i have so far
public class Program1 {
public static void main(String[] args)
{
int[] one = { 2 };
int[] two = { 1, 0 };
System.out.println(allLess(one, two));
}
public static boolean allLess(int[] one,int[] two)
{
if (one.length != two.length)
{
int len = 0;
if(one.length <= two.length)
{
len = one.length;
}
if(two.length < one.length)
{
len = two.length;
}
boolean[] boo = new boolean[len];
for(int i = 0; i < len; i++)
{
if(one[i] < two[i])
{
boo[i] = true;
}
else
{
boo[i] = false;
}
}
if(Arrays.asList(boo).contains(false))
{
return false;
}
else
{
return true;
}
}
for (int i = 0; i < one.length; i++)
{
if (one[i] >= two[i])
{
return false;
}
}
return true;
}
}
Perhaps you could try something like this:
public static boolean allLess(final int[] array1, final int[] array2){
for(int i = 0; i < Math.min(array1.length, array2.length); i++)
if(array1[i] >= array2[i])
return false;
return true;
}
//this way works too. did you get program 3 done yet? Its giving me issues
import java.lang.Math.*;
public class Program1 {
public static boolean allLess(int[] one, int[] two) {
if (one == null || two == null) {
return false;
}
for (int i = 0; i < Math.min(one.length, two.length); i++) {
if (two[i] <= one[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(" ");
}
}

Categories

Resources