Java beginner exercise with methods - java

I am real beginner in Java and I have one simple exercise where I need to convert m/h into km/h using a method and a return from it.
I have to define 2 situations: if km/h < 0 return -1 (error) and if km/h > 0 return km/h * 1.609 (value in m/h).
I tried everything I could think of but I either get a no return statement error or no output when I try to run it.
I can't understand why even if I gave it more than one return option it just doesn't work whatever the value is. I could use System.outprintln or String but the exercise specify I must use a return method.
here is my code, written in IntelliJ:
package EXERCISE;
public class Main {
public static void main(String[] args) {
toMilesPerHour(0);
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour > 0) {
return kilometersPerHour * 1.609d;
}
else if (kilometersPerHour == 0) {
return 0;
}
return kilometersPerHour * 1.609;
// if I don't write return here it gives me no return statement error,
// if I write it, it gives me no output with value > or < 0 but no error.
}
}

public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else {
return kilometersPerHour * 1.609;
}
}

Try it like this:
public static double toMilesPerHour(double kilometersPerHour) {
return (kilometersPerHour > 0 ? kilometersPerHour*1.609 : -1;
}
You could also throw an exception if speed is negative:
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) throw new IllegalArgumentException("speed cannot be negative");
return kilometersPerHour*1.609;
}

Even if you use a method, you have to print the returned value:
package EXERCISE;
public class Main {
public static void main(String[] args) {
System.out.println(toMilesPerHour(0));
}
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour > 0) {
return kilometersPerHour * 1.609d;
}
else if (kilometersPerHour == 0) {
return 0;
}
return kilometersPerHour * 1.609;
//if I don't write return here it gives me no return statement error,
//if I write it, it gives me no output with value > or < 0 but no error.
}
}
Furthermore, you can get rid of the return statement at the end:
public static double toMilesPerHour(double kilometersPerHour) {
if (kilometersPerHour < 0) {
return -1;
}
else {
// you don't need to check if kilometersPerHour is 0, since every number multiplied with 0 is 0
return kilometersPerHour * 1.609;
}
}

If you use if()... else you have exactly two options. Either you go into the if clause and do whats there, or you go into the else clause. If if-clause and else-clause both have a return-statement, everything goes fine.
But you don't have if-else-clauses! You have if-else-if-clauses!
If the if-clause doesn't hold, you go into the else-clause, which again has an if-clause and so on. Finally you don't have a default else clause.... if you don't get into the first if-clause, you check in the else-clause, if the condition holds. If not, you check the condition in the next else clause. The last return-statement finally is the default else clause. We all, as humans, see, that every condition (<, == >) is covered, but the compiler doesn't see that!

The reason compiler gives you "no return statement" error is because you didn't cover all possible cases with your ifs: there is Double.NaN, which is not equal to 0 (or any other value, for that matter, including itself) and neither greater nor lesser than 0.
Also, compiler doesn't analyze your code deep enough to check if you covered all possible variants anyway: if you replace double with long, the result is the same - the compiler will see the reachable branch that doesn't return anything, and so it produces an error.
To fix an error, you need to have all branches return something:
if (kilometersPerHour < 0) {
return -1;
}
else if (kilometersPerHour == 0) {
return 0;
}
// Note: I don't have explicit check for NaN,
// because any arithmetic on NaN produces NaN,
// which would be the correct result for this function.
// So I let the "*" operator to check for NaN instead.
return kilometersPerHour * 1.609;

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;

Bad return type in lambda expression in java

public static final Comparator<Summary> COMPARATOR = (courseModel1, courseModel2) -> {
if (courseModel1.department.compareTo(courseModel2.department) > 0) {
return courseModel1;
}
if (courseModel1.department.compareTo(courseModel2.department) < 0) {
return courseModel2;
}
if (courseModel1.department.compareTo(courseModel2.department) == 0) {
if (courseModel1.number.compareTo(courseModel2.number) > 0) {
return courseModel1;
}
if (courseModel1.number.compareTo(courseModel2.number) < 0) {
return courseModel2;
}
if (courseModel1.number.compareTo(courseModel2.number) == 0) {
if (courseModel1.title.compareTo(courseModel2.title) > 0) {
return courseModel1;
}
if (courseModel1.title.compareTo(courseModel2.title) < 0) {
return courseModel2;
}
}
}
// (ERROR: missing a return statement here)
};
As mentioned in the documentation for the method compare
Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
So your code needs to return an integer instead of the objects.
If the first argument is less than the second, return -1,
If the first argument is greater than the second, return 1,
If the objects are equal return 0.
Currently, it's returning one of the parameters.
The cause of missing a return statement compilation error is a missing branch, your code can either use if/else to ensure all branches are covered, instead of just ifs, or add a default return value at the end.
Edit, more detailed info below:
What happens if the if pointed by the blue arrows is false? There's no code to indicate it.
First, Comparators return an int describing the relationship between two objects. They do not return the objects under comparison.
So you may want to simplify your comparator as follows. This works by first checking for equality(== 0). If not equal, return either -1 or 1 depending on the subsequent comparison (it must be one or the other). Otherwise, continue to the next test and check for equality of numbers and if equal, just return the numeric result of comparing titles, regardless. It would look like this.
Comparator<Summary> COMPARATOR =
(courseModel1, courseModel2) -> {
if (courseModel1.department.compareTo(
courseModel2.department) != 0) {
return courseModel1.department
.compareTo(courseModel2.department);
}
if (courseModel1.number
.compareTo(courseModel2.number) != 0) {
return courseModel1.number
.compareTo(courseModel2.number);
}
// in the last case, just return the overall comparison (-1,0, or 1).
return courseModel1.title
.compareTo(courseModel2.title);
};
But this could be simplified further by using the methods provided by the Comparator interface. In each case it will return the result of comparing Summary fields based which is less or greater. If they are equal, the comparator will then try the number, followed by the title.
Comparator<Summary> comp =
Comparator.comparing(Summary::getDepartment)
.thenComparing(Summary::getNumber)
.thenComparing(Summary::getTitle);
Regardless of the form of the Comparator, you would use it like this.
Summary sum1 = ...
Summary sum2 = ...
int cmp = COMPARATOR.compare(sum1,sum2);
if (cmp < 0) {
// do something with sum1.
} else if (cmp > 0) {
// do something with sum2.
} else {
// take some action as required.
}
The class being compared
class Summary {
public String department;
public String title;
public Integer number;
public String getDepartment() {
return department;
}
public String getTitle() {
return title;
}
public Integer getNumber() {
return number;
}
}

Given an array of numbers, the task is to print only those numbers which have only 1, 2 and 3 as their digits

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

Is it possible to write return statement in if block using java?

I want to return Vector according to if block but the code gives me the following error: Add return statement.
Is it possible to write return statement in if block?
public static int[] zeroVectorBinning1( ImageFloat32 angle,ImageFloat32 Magnitude )
{
for (int NumberOFChanks=0;NumberOFChanks<locations_original.size();NumberOFChanks++)
{
for(int i=0;i<angle.getHeight();i++)
for(int j=0;j<angle.getWidth();j++)
{
int orientaionVal=(int) angle.get(j, i);
if(orientaionVal<=0)
{int magnitudeVal=(int) Magnitude.get(j, i);
int[] Vector = new int[19];
Vector=zeroVector(19);
Vector[0]=magnitudeVal;
return Vector;
}
else if(orientaionVal<=20)
{int magnitudeVal=(int) Magnitude.get(j, i);
int[] Vector = new int[19];
Vector=zeroVector(19);
Vector[1]=magnitudeVal;
return Vector;
}
else(orientaionVal >= 0 && orientaionVal <=20)
{
int magnitudeVal=(int) Magnitude.get(j, i);
int[] Vector = new int[19];
Vector=zeroVector(19);
Vector[0]=magnitudeVal;
Vector[1]=magnitudeVal;
return Vector;
}
}
}
}
There's nothing wrong in having return statements in if blocks, but your method must have a return statement in any execution path.
Your for loops may never be executed (if, for example, locations_original.size() is 0), in which case none of the if blocks that contain the return statements will be reached. Therefore you must add a return statement following the loops.
Yes,
But your function still not return anything in the end, so you have to return something, even null.
So when you call this function, it should ne looking like this:
int[] fuctionResult = zeroVectorBinning1(....);
if (fuctionResult != null){
....
}
You could resolve this in two ways:
At the end either throw an exception just before completing the method.
Or at the end just return null.
Reason why compiler is complaining because, if locations_original.size() returns 0 then this method would never return anything which contradicts with what you said in your method that it will return an int array.
It is possible. But you need a return statement for every cases. Also if your for loop is never executed.
so add return null; at the end of your method.
Yes it is possible. Follow the code snippet for explanation.
public class TestSample {
public static void main(String... w){
int h = new TestSample().call();
System.out.println(h);
}
public int call(){
int j =0;
for(int i=0;i<10;i++){
if(i==5){
return i;
}
}
return j;
}
}
This prints 5.
public int getValue(){
final int value = 3;
if(value==1){
return 1;
}
else if(value==2){
return 2;
}
else if(value==3){
return 3;
}
else{
return -1;
}
// no return because "else" covers all cases
}
In this case you have an "else" at the end, so every case is covered. but if you leave the else ...
public int getValue(){
final int value = 3;
if(value==1){
return 1;
}
else if(value==2){
return 2;
}
else if(value==3){
return 3;
}
return -1;
// ... you have to return something at the end of the method, because value could be >3 or < 1 and the code under the last else if will be executed
}
The problem is your if/else-if/else parse is not complete, what does else with a condition like:
else(orientaionVal >= 0 && orientaionVal <=20)
mean? It's odd. Just omit the condition (orientaionVal >= 0 && orientaionVal <=20) of the last else sentence (and it's not logically correct when orientaionVal is 0 or 20), or there will be no default else in the scope.
When return in the scope of a if sentence, we must make sure that under any condition there is a return, so:
Make a default return out of the if-else scope
Or be sure that the condition judgement is complete and there is a return under any condition.
So
Correct:
if(condition){
return;
}
return;
Correct:
if(condition){
return;
}else if(anotherCondition){
return;
}else{
return;
}
Wrong:
if(condition){
return;
}
// no return ...
Wrong:
if(condition){
return;
}else if(anotherCodition){
return;
}
// no return ...

Linked List Null Error

I have written the following code to compute the sum of all the even entries in a LinkedList. However, I keep getting a NullPointerException because of the line where I use (n.getNext).getNext().
Could any of guys tell me as to why this is happening?
Here is the piece of code I'm referring to:
public int sumEven() {
return sumEven(head);
}
// private sumEven helper
private int sumEven(IntListNode n) {
int nodeNumber=1;
int count=0;
if(n.getNext() == null && nodeNumber%2 == 0) {
return n.getValue();
} else if((n.getNext()).getNext() == null && nodeNumber%2 == 0) {
return n.getValue();
} else {
nodeNumber++;
if(nodeNumber%2 == 0) {
count+=n.getValue();
return count+ sumEven(n.getNext());
} else {
return count + sumEven(n.getNext());
}
}
}
Because what if: In the first if statement n.getNext() is null but nodeNumber%2 is not equal to 0
So you go to the next if statement which says n.getNext().getNext() == null where already the first getNext() is null since it passed the first part of the previous if statement but failed the if statement because of the nodeNumber%2 == 0 part.
Ex: nodeNumber = 1 and n.getNext() = null
First if(true && false) => false
Second if(ERROR) Cuz the previous if statement has the first part true which says n.getNext() is null
There are many problems in the code. How about rethink the strategy? If you want to make it recursive, you can assume that the private method sumEven() will always be called with an even node. Then all that private method does is add up whatever that it is called with.
The following code is not tested but shows what I mean.
public int sumEven() {
return sumEven(head,0);
}
private int sumEven(IntListNode n, int total) {
if(n==null) return total;
total += n.getValue(); // sums up running total
if(n.getNext()==null) return total;
return sumEven(n.getNext().getNext(),total); // calls next even node with current running total
}

Categories

Resources