Why is return executed twice - java

In this case the value does match and the value of boolean is set to true,however return is called twice and does update the value to false.Can anyone suggest what am I missing here?.
public class BinSearch {
public static void main(String[] args) {
BinSearch bin=new BinSearch();
int arr[]= {2,4,6,8,10,12,14,16};
boolean b=bin.binSearch(arr,0,arr.length-1,12);
System.out.println("Number found "+b);
}
public boolean binSearch(int arr[],int low,int high,int val)
{
int mid=(low+high)/2;
if(arr[mid]==val)
{
return true;
}
else if(arr[mid]>val)
{
binSearch(arr,mid+1,high,val);
}
else
{
binSearch(arr,low+1,mid,val);
}
return false;
}
}

You're missing two returns when calling the recursion:
return binSearch(...);
If you don't write them, the method will ignore the result of the recursion and just return false at the end. After doing that, the last return will be unnecessary and should be deleted. Finally, you need to check the case when low > high, that means that the element was not found.

Because your return false; overrides everything except for a case when the value is found on the first run and no recursive call is invoked. Please return for each recursive call. Additionally, you must check if your low boundary is less or equal to the high boundary. So, your code could be as follows:
public boolean binSearch(int arr[],int low,int high,int val)
{
if (low <= high) {
int mid=(low+high)/2;
if(arr[mid]==val) {
return true;
} else if(arr[mid]>val) {
return binSearch(arr,mid+1,high,val);
} else {
return binSearch(arr,low+1,mid,val);
}
}
return false;
}

You can also try the following code in binSearch function. The only change made is that there is a boolean type variable capturing the value returned in the recursive calls and finally returning this varaible.
public boolean binSearch(int arr[],int low,int high,int val) {
int mid=(low+high)/2;
boolean returnValue = false;
if(arr[mid]==val) {
return true;
} else if(arr[mid]>val) {
returnValue = binSearch(arr,mid+1,high,val);
} else {
returnValue = binSearch(arr,low+1,mid,val);
}
return returnValue;
}

public class BinSearch {
public static void main(String[] args) {
BinSearch bin=new BinSearch();
int arr[]= {2,4,6,8,10,12,14,16};
boolean b=bin.binSearch(arr,0,arr.length-1,16);
System.out.println("Number found "+b);
}
public boolean binSearch(int arr[],int low,int high,int val)
{
int mid=(low+high)/2;
//boolean b = false;
while(low<=high)
{
if(arr[mid]==val)
{
return true;
}
else if(val>arr[mid])
{
return binSearch(arr,mid+1,high,val);
}
else
{
return binSearch(arr,low+1,mid,val);
}
}
return false;
}
}

Related

Return type function in java

public class prime
{
public static boolean Isprime(int n)
{
boolean Isprime = true;
for(int i=2;i<n;i++)
{
if(n%2==0)
{
Isprime = false;
break;
}
}
return Isprime;
}
public static void main(String args[])
{
System.out.println(Isprime(5));
}
}
can we make a boolean return type function in this case without initializing the Isprime variable?
if i make an else statement with returning true (so that there will be no need to initialize the variable) i can do return Isprime after the for loop, but it's giving me an error because i didn't initialize the isprime variable
public class prime
{
public static boolean Isprime(int n)
{
for(int i=2;i<n;i++)
{
if(n%2==0)
{
return false;
}
}
return true;
}
public static void main(String args[])
{
System.out.println(Isprime(6));
}
}

Exception in thread "main" java.lang.ArrayStoreException when store object into array

This is my whole code, the problem requires me to use Array for solution.
import java.lang.reflect.Array;
public class MyStack<T> {
public MyStack (Class<T[]> _class,int size){
final T[] values = (T[]) Array.newInstance(_class,size);
this.values = values;
this.size=size;
}
private T[] values;
private int top=0,size;
public void push(T nextElement){
if(isFull()){
System.out.println("full");
}
else {
values[top++] = nextElement;
}
}
public T pop(){
if(isEmpty()) {
System.out.println("empty");
return null;
}
else {
return values[top--];
}
}
public boolean isEmpty(){
if (top==0)return true;
return false;
}
public boolean isFull(){
if(top==size-1)return true;
else return false;
}
public static void main(String args[]){
MyStack<Integer> myStack = new MyStack<Integer>(Integer[].class,9);
for (int i =0;i<10;i++)
{
myStack.push(i);
}
while(!myStack.isEmpty()){
System.out.println(myStack.pop());
}
}
}
When i compile it it throws Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at values[top++] = nextElement; no matter which type i used from String, Integer or any other Objects.
Is there a way to fix this problem ?
You constructor takes a Class<T[]> but should take a Class<T>, also you don't need a variable shadow on values. I'd write it like
public MyStack(Class<T> _class, int size) {
this.values = (T[]) Array.newInstance(_class, size);
this.size = size;
}
You don't need if else chains for isEmpty (just return the condition you are testing directly) - like
public boolean isEmpty() {
return top == 0;
}
Or for isFull
public boolean isFull() {
return top == size - 1;
}

NumberVerify: missing return statement

import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
if((num%2)==0)
{
boolean yes = true;
return true;
}
}
public static boolean isEven( int num )
{
if((num%2)!=0)
{
boolean yes = false;
return false;
}
}
}
The error messages say "missing return statements" on the }'s.
I tried adding
return true;
after the set of braces nested by
if((num%2)==0)
and did something similar with the
if((num%2!=0)
nest, although with
return false;
That only caused the isOdd to pop up as true and isEven to pop up as false regardless of the inputted number itself.
Here is the runner program.
import static java.lang.System.*;
import java.util.Scanner;
public class NumberVerifyRunner
{
public static void main ( String[] args )
{
//add in input
System.out.println("5 is odd :: " + NumberVerify.isOdd(5));
System.out.println("5 is even :: " + NumberVerify.isEven(5));
System.out.println("0 is odd :: " + NumberVerify.isOdd(0));
System.out.println("0 is even :: " + NumberVerify.isEven(0));
System.out.println("2 is odd :: " + NumberVerify.isOdd(2));
System.out.println("2 is even :: " + NumberVerify.isEven(2));
//add in more test cases
}
}
How do I fix the missing return statements in the NumberVerify class?
You need to return a value if the 'if' clause is not satisfied.
All code blocks need to return a value. This solution should work well.
public static boolean isOdd(int num) {
if ((num % 2) == 0) {
return true;
} else {
return false;
}
}
public static boolean isEven(int num) {
if ((num % 2) != 0) {
return false;
} else {
return true;
}
}
Try adding return false after the first if statement and return true after the second.
Also you could just return the result of num%2==0 without the if statement due to the fact that num%2==0 is a boolean value. So you could also delete the if statements and do return( num%2)==0;
For the other one do return (num%2 )!=0;
isOdd and isEven must return boolean for all branches.
This will work
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
return numr%2 == 1;
}
public static boolean isEven( int num )
{
return num % 2 == 0;
}
}
In java your return statement is the last statement. In your case just change whit following code
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd(int num)
{
if(num%2 == 0)
{
return true;
}
return false;
}
public static boolean isEven( int num )
{
if(num%2 !=0 )
{
return true;
}
return false;
}
}
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
if((num%2)!=0)
{
boolean yes = true;
}
return yes;
}
public static boolean isEven( int num )
{
if((num%2)==0)
{
boolean yes = true;
}
return yes;
}
}
Your code have the return statement is out of the scope.
Method signature have return the boolean value but you put return statement if() control scope only so you change the public scope(current method scope).
Your All code path will not return values:
Consider your code :
public static boolean isOdd( int num )//Assume num as 7
{
if((num%2)==0)// 7 % 2 will be 1 , condition fails
{
boolean yes = true;
return true;// this statement won't be executed
}
// you have no return statement here
}
import static java.lang.System.*;
public class NumberVerify
{
public static boolean isOdd( int num )
{
boolean isOddNumber = (num %2 ) !=0
return isOddNumber;
}
public static boolean isEven( int num )
{
boolean isEvenNumber = (num %2 )==0
return isEvenNumber;
}
}
you give a return to a if and forgot the else. In your method isOdd() the return is only in the if not in the method. you may change your code like this.
public static boolean isOdd( int num )
{
if((num%2)==0)
{
boolean yes = true;
return true;
} else {// you must add the else
return true;// return a boolean value here.true or false,it's up to you.
}
// Or add a return below without add the else.
return ture;// true or false,it's up to you.
}
public static boolean isEven( int num )
{
if((num%2)!=0)
{
boolean yes = false;
return false;
} else {// you must add the else
return true;// return a boolean value here.true or false,it's up to you.
}
// Or add a return below without add the else.
return ture;// true or false,it's up to you.
}

Using a method after casting in Java

I have written the code:
public int compareTo(Object w) {
//w = (Word)w
if(this.count > (Word) w.getCount()) {
return -1;
} else if (this.count < (Word) w.getCount()) {
return 1;
} else {
return 0;
}
}
I have written the class Word. It implements Comparable so I must use the Object parameter for the compareTo() method.
However, I need the object to use a method in the Word class. I get an error if I cast and was wondering if I am doing something wrong or if I need to try something else?
Word class:
package comp10152_lab3;
public class Word implements Comparable{
private int count;
private String word;
public Word(String word) {
this.word = word;
this.count = 1;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
#Override
public int compareTo(Object w) {
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
public void countUp() {
count++;
}
#Override
public String toString() {
return word + "(" + count + ")";
}
#Override
public boolean equals(Object w) {
return w.equals(word);
}
}
The equals class is suppose to be that way, as per instruction.
The error I am getting is on the w.getCount() which is a "missing symbol" error.
This is the code that you need:
public int compareTo(Object o) {
Word w = (Word) o;
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
The problem that you were having was due to the fact that w was of the type Object, the statement w = (Word) w would not do what you wanted. The second part of the problem has to do with the precedence of the cast operator in Java. When you do (Word)w.getCount(), the getCount() part gets evaluated first, meaning that you were effectively doing (Word) <some int>. What you could have done was wrap it in parentheses like ((Word) w).getCount() to solve that problem.
You should implement Comparable<Word> so that the compareTo method is public int compareTo(Word w). Also you can simplify your compareTo code:
public class Word implements Comparable<Word> {
private int count;
public int compareTo(Word w) {
return w.count - this.count;
}
}
If you can't use java generics then you can still do your compareTo in one line:
public int compareTo(Object w) {
return ((Word) w).count - this.count;
}

Having trouble with java class methods

ok so my assignment I'm supposed to write a class that stores a temperature that the user gives and checks it with the set parameters to see if Ethy/Oxygen/Water are either freezing or boiling and then display it at the end which ones will be freezing/boiling at the temperature that they entered. I have the majority of both the class and tester completed but I'm getting several errors on my code. I'm not asking anyone to give me the answer but if you could tell me what I'm doing wrong I would greatly appreciate it. Here is my code for class:
public class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private Boolean isEthylFreezing(int temperature) {
if (temperature <= -173) {
return true;
} else {
return false;
}
}
private Boolean isEthylBoiling(int temperature) {
if (temperature >= 172) {
return true;
} else {
return false;
}
}
private Boolean isOxygenFreezing(int temperature) {
if (temperature <= -362) {
return true;
} else {
return false;
}
}
private Boolean isOxygenBoiling(int temperature) {
if (temperature >= -306) {
return true;
} else {
return false;
}
}
private Boolean isWaterFreezing(int temperature) {
if (temperature <= 32) {
return true;
} else {
return false;
}
}
private Boolean isWaterBoiling(int temperature) {
if (temperature >= 212) {
return true;
} else {
return false;
}
}
public String showTempinfo() {
if (isEthylFreezing()) {
System.out.println("Ethyl will freeze");
}
if (isEthylBoiling()) {
System.out.println("Etheyl will boil");
}
if (isOxygenFreezing()) {
System.out.println("Oxygen will freeze");
}
if (isOxygenBoiling()) {
System.out.println("Oxygen will Boil");
}
if (isWaterFreezing()) {
System.out.println("Water will freeze");
}
if (isWaterBoiling()) {
System.out.println("Water will boil");
}
}
}
and the code for my tester is below:
import java.util.Scanner;
public class FreezingBoilingTester {
public static void main(String[] args) {
int temperature;
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(0);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
temperature = scan.nextInt();
System.out.println(showTempinfo());
}
}
1) don't pass the temp inside methods, because you already have this value in member variable.
2) you can change if (condition) then true else false into return (condition) and it will be the same result, just for readability .
3) you should return boolean not Boolean wrapper until you need the wrapper.
public final class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private boolean isEthylFreezing() {
return (temperature <= -173);
}
private boolean isEthylBoiling() {
return (temperature >= 172);
}
private boolean isOxygenFreezing() {
return (temperature <= -362);
}
private boolean isOxygenBoiling() {
return (temperature >= -306);
}
private boolean isWaterFreezing() {
return (temperature <= 32) ;
}
private boolean isWaterBoiling() {
return (temperature >= 212);
}
public String showTempinfo() {
StringBuilder result = new StringBuilder();
if (isEthylFreezing()) {
result.append("Ethyl will freeze");
result.append("\n");
}
if (isEthylBoiling()) {
result.append("Etheyl will boil");
result.append("\n");
}
if (isOxygenFreezing()) {
result.append("Oxygen will freeze");
result.append("\n");
}
if (isOxygenBoiling()) {
result.append("Oxygen will Boil");
result.append("\n");
}
if (isWaterFreezing()) {
result.append("Water will freeze");
result.append("\n");
}
if (isWaterBoiling()) {
result.append("Water will boil");
result.append("\n");
}
return result.toString();
}
}
Main:
import java.util.Scanner;
public class FreezingBoilingTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
int temperature = scan.nextInt();
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(temperature );
System.out.println(temp1.showTempinfo());
}
}
updated:
you can use String concatenation:
String result = "";
if ( condition ) {
result += "new result";
result += "\n";
}
but this is not recommended in term of performance, because each += operation will create another String object in memory holding the new result.
The problem is that your private methods are taking in a temperature and yet, you are not passing one in for your showTempinfo() method. Try removing the input parameters and using the temp set in the class. Also, you need to somehow set the temp before you call showTempinfo().
Hope this helps.
You're not passing the input that the user is giving you into the constructor for your FreezingBoilingPoints class. You're initializing that class with 0 and then asking for a temperature from the user. There's no relationship between the temperature the user provided and the class that you're using to test it.
You need to construct your FreezingBoilingPoints object in your main method, then call showTempinfo() on it. Also, your private calc methods should use the member variable; there's no need to take it as a parameter.
You need to pass the user input, temperature, into your FreezingBoilingPoints constructor. Also, the method showTempInfo() is instance specific. For example, you need to instantiate your object, temp1, by passing the user input with the constructor and then invoke temp1.showTempInfo()
Here we go:
1) All your "is..." methods are expecting for an int parameter, however when you're calling them, you're not passing anything. Remove the int parameter from either the method implementation or the method calls
2) You're missing a closing bracket for the method isWaterBoiling;
3) You marked the method "showTempinfo" as returning String, but you are not returning anything for that method. Either add the return command or remove the "String" from the method signature.
In your showTempinfo(), you try to do isEthylFreezing().
But it can't work ... isEthylFreezing is waiting for an int ... but it gets nothing ...

Categories

Resources