Java Program: return statements not working - java

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

Related

return statement in boolean method

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

Leetcode 110. Balanced Binary Tree Can I ask why my solution is wrong?

The original question is attached here: https://leetcode.com/problems/balanced-binary-tree/description/
public class BalancedBinaryTree {
static boolean balance = true;
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
}
public int depth(TreeNode root) {
if (balance) {
if (root == null)
return 0;
int lengthOfLeft = depth(root.left);
int lengthOfRight = depth(root.right);
if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
balance = false;
}
return Math.max(lengthOfLeft, lengthOfRight) + 1;
} else {
return 0;
}
}
Try this.
Basically, you should have been reseting the balance back to true, because going from a test where the output is positive (expect true) to one where it is negative (expect false) will matter.
static boolean balance = true;
public boolean isBalanced(TreeNode root) {
balance = true;
if (root == null)
return true;
return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
}
public int depth(TreeNode root) {
if (balance) {
if (root == null)
return 0;
int lengthOfLeft = depth(root.left);
int lengthOfRight = depth(root.right);
if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
balance = false;
}
return Math.max(lengthOfLeft, lengthOfRight) + 1;
} else {
return 0;
}
}

Using stack to check equal number of letters and digits in password

I have to write a program to check a password whereby the password should
should be at least 8 characters long
contain only letters and digits(special characters)
contain an equal number of letters and digits
The program should check if it is valid and displays an appropriate message.
Also, only the stack class should be used as the data structure.
Here is what I have come up with so far:
public class dsa_1c {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
String pass;
System.out.println("Enter a password");
pass= sc.nextLine();
if(checkPass(pass)){
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean checkPass(String password){
Stack<Character> stack= new Stack<Character>();
int count1=0, count2=0;
if(password.length()<8){
return false;
}
else{
for(int i=0; i<password.length();i++){
char c= password.charAt(i);
if (!Character.isLetterOrDigit(c)){
return false;}
if(Character.isLetterOrDigit(c)){
stack.push(c);
}
char top= stack.peek();
if(Character.isLetter(top)){
count1++;
stack.pop();
}
else if(Character.isDigit(top)){
count2++;
stack.pop();
}
if(count1==count2){
return true;
}
if(!stack.isEmpty()){
return false;
}
}
}
return true;
}
}
The program when run displays "Valid Password" for any password I type in with more than 8 characters and with no special characters.
It's this part which is apparently the issue
if(count1==count2){
return true;}
because when I change it
if(count1!=count2)
return false; }
it returns Invalid Password for any valid ones.
It's return true in the end that causes an issue. Instead of comparing two counts and returning the values, you can just use return count1 == count2;. Below is an example:
public static boolean checkPass(String password) {
Stack<Character> stack = new Stack<Character>();
int count1 = 0, count2 = 0;
if (password.length() < 8) {
return false;
} else {
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else {
stack.push(c);
}
}
while(!stack.isEmpty()){
char c = stack.pop();
if(Character.isLetter(c)){
count1++;
}else{
count2++;
}
}
return count1 == count2;
}
}
Using a stack seems like overkill to me - it's enough to iterate over the characters, count the digits and the letters, and make sure they have the same number:
private static boolean isValidPassword(String password) {
int letterCount = 0;
int digitCount = ;
for (int i = 0; i < password.length(); ++i) {
char c = password.charAt(i);
if (Character.isLetter(c)) {
++letterCount;
} else if (Character.isDigit(c)) {
++digitCount;
} else {
return false;
}
}
return (letterCount + digitCount) >= 8 &&
letterCount == digitCount;
}
Assuming this is an exercise just to manipulate a stack, here is my 2 cents:
public class dsa_1c {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a password");
String pass = sc.nextLine();
if (checkPass(pass)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
private static boolean checkPass(String pass) {
boolean result = false;
if (pass.length() == 8) {
Stack stack = new Stack();
for (char current : pass.toCharArray()) {
if (stack.isEmpty()) {
stack.push(current);
continue;
}
char previousChar = stack.pop();
if (sameType(current, previousChar)) {
stack.push(previousChar);
stack.push(current);
}
}
if (stack.isEmpty()) {
result = true;
}
}
return result;
}
public static boolean sameType(char current, char previousChar) {
boolean result = false;
if (Character.isAlphabetic(current) && Character.isAlphabetic(previousChar)) {
result = true;
}
else if (Character.isDigit(current) && Character.isDigit(previousChar)) {
result = true;
}
return result;
}
static class Stack extends ArrayList {
public static final char NULL_CHARACTER = 0x0;
public void push(Character letter) {
add(letter);
}
public Character pop() {
Character result = NULL_CHARACTER;
if (!isEmpty()) {
result = (Character)remove(size()-1);
}
return result;
}
}
}

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

Simple Java Method Error when Returning

I'm learning methods and was trying to write code that basically tells if a number is prime. However, I keep encountering the error:
error: cannot find symbol
return(isPrime);
^
error: illegal start of type
return(isPrime);
This is my current code (i hope i'm using the method correctly):
import java.util.Scanner;
public class DoublePalindromicPrimes{
public static void main(String args[]){
Scanner in= new Scanner(System.in);
System.out.println("Please enter a number:");
int n = in.nextInt();
//prime(n);
boolean resultPrime = prime(n);
if (resultPrime){
System.out.println("This is a prime");
}
else {
System.out.println("This is not a prime");
}
}
public static boolean prime(int x){
for (int i=2;i<x;i++){
boolean isPrime;
if (x%i==0){
isPrime=false;
}
else{
isPrime=true;
}
}
return isPrime;
}
}
Any help is appreciated!
public static boolean isPrime(int x)
{
if(x > 2) {
if(x%2 == 0) {
return false;
} else {
int sqrt = (int)(Math.sqrt(x));
for(int i=3;i<=sqrt;i+=2) {
if(x%i == 0) {
return false;
}
}
}
return true;
} else if(x==2) {
return true;
} else { //1, 0, and negatives
return false;
}
}
change it to
return isPrime;
note the space and make declaration out of isPrime for loop
You declared isPrime inside your loop, so the return statement can't see it. Move it outside the loop.
public static boolean prime(int x) //throws InvalidNumberException
{
if (x <= 0)
{
//throw new InvalidNumberException("The number is invalid");
}
int squareRoot = (int)(Math.sqrt(x));
for (int i = 2; i <= squareRoot; i++)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
This is an optimized prime validator.

Categories

Resources