Java main return error

How to fix «Missing return statement» in java

missing return statement > , even though I put the return x after the condition. Thanks a lot for your help 🙂 Solution 1: your method expects a return statement your are returning the value on the part you should also return a value when condition fails change your code something like the below Solution 2: The statement you have provided is inside the block which means The Return statement wouldn’t be executed or reached if the condition is false.

How to fix «Missing return statement» in java

Im making a java method for an android app that returns the directory the app should be working in in the External Directory.

I’m having a problem handling the returns and I don’t know how to fix the error of «missing return statement».

public String getpath() < String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) < String extdir = Environment.getExternalStorageDirectory().getAbsolutePath(); File path = new File(extdir, "App"); if(path.exists()) < return path.getAbsolutePath(); >else < checkandmakepath(); getpath(); >> else < Toast.makeText(this, "Could not access External Directory!", Toast.LENGTH_LONG).show(); Intent to_main = new Intent(this, MainActivity.class); startActivity(to_main); MainActivity.this.finish(); >> 

Implies that your method will return a String object, which is only done inside your if statements. Place this at the end of your method to ensure something is always returned no matter what conditions you go through. (You don’t need to do this at the end of every else since you already return at the if branch.)

If you don’t want to exit the method until a path is returned, you can do a while loop for it, but this may cause it to be infinite so this is best handled by whatever is calling your method instead.

add return statement in your both else blocks

Every method in java which has a return type in its signature should return a value. In your code there are multiple execution paths due to the if/else statements. And you are doing the return only in one of the if statement. But in scenarios where that if is not executed, the flow will go to other else blocks and there is no return statement, which is causing the compiler to complain.

Depends on what do you want. But I will do sth like below

public String getpath() < String returnPath = null; String state = Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)) < String extdir = Environment.getExternalStorageDirectory().getAbsolutePath(); File path = new File(extdir, "App"); if(path.exists()) < return path.getAbsolutePath(); >else < checkandmakepath(); returnPath = getpath(); >> else < Toast.makeText(this, "Could not access External Directory!", Toast.LENGTH_LONG).show(); Intent to_main = new Intent(this, MainActivity.class); startActivity(to_main); MainActivity.this.finish(); >return returnPath; 

Error in Java: «missing Return statement», The compiler is telling you that you don’t have a return statement for all possible code paths. While that is not possible in your case, the compiler isn’t built to figure that out: the path in question is the path where none of the if blocks get triggered by the values passed in for card1 and card2.

Java:17: error: missing return statement

I wrote code to get a number from the user, then check whether the number is prime.

import java.util.*; public class hanoo < public static void main(String args[]) < Scanner input = new Scanner(System.in); System.out.println("please enter an integer number"); int number = input.nextInt(); System.out.println(num(number)); >public static String num(int number) < for (int i = 2; i < number; i++) < if (number % i != 0) return "it is prime"; else return "it is not prime"; >> > 
q1.java:17: error: missing return statement > ^ 1 error ----jGRASP wedge2: exit code for process is 1. 

Your function currently does not necessarily return anything. This is the case when number is smaller than or equal to 2. You should add a return statement outside of your for loop, so that the function will always return something.

Side note: The logic to decide whether a number is a prime or not is wrong. If the current function was valid, it would return it is prime if the number was odd and it is not prime if the number was even.

Читайте также:  Html image embedded in text

While the other answers havd correctly pointed out why you are getting the error, I feel obliged to point out that your code (and other answers here) will not correctly indicate whether the number is prime, or not. Try this instead:

public static String num(int number) < for (int i = 2 ; i> return "it is prime" ; > 

If number variable is less or equal then for loop will not run. So return statement in for statement will not work. To fix your compilation error you should add return statement after for block. Your code will look something like this:

public static String num(int number) < for (int i = 2 ; ireturn "some message"; > 

the reason your for loop not execute by condition failed, what is the return value. so it is a error. try this..

public static String num(int number) < String result = ""; for (int i = 2 ; ireturn result; > 

Java:17: error: missing return statement, If number variable is less or equal then for loop will not run. So return statement in for statement will not work. To fix your compilation error you should add return statement after for block. Your code will look something like this:

Java:14: error: missing return statement > [duplicate]

I’ve been learning Java for two weeks and I’m stuck on this exercise. This might be a very simple question but I couldn’t find the problem yet. I’m trying to test the first method I’ve written in this algorithme :

 1 import java.util.*; 2 public class stationnement < 3 public static void main (String[] args) < 4 int j = jour(); 5 System.out.println(j); 6 >7 public static int jour() < 8 Scanner sc = new Scanner(System.in); 9 System.out.println("Rentrez le jour"); 10 int x = sc.nextInt(); 11 if (x >0 && x <=31)12 > 13 14 > 

When I compile my code I get stationnement.java:12: error: missing return statement > , even though I put the return x after the condition. I tried deleting the if condition and it worked. But I would like to know what’s the problem here. Isn’t correct to place the condition there?

Thanks a lot for your help 🙂

your method public static int jour() . expects a return statement

your are returning the value on the if part if (x > 0 && x

you should also return a value when if condition fails

change your code something like the below

The return statement you have provided is inside the if block which means The Return statement wouldn’t be executed or reached if the condition is false. You must provide a return statement outside the if statement which will be used even if the condition is false.The function must return something since its not void .But in this case,it doesn’t if the condition is not satisfied.You will have to use an ‘else’ block and return 0.

How to fix «missing return statement» error in java?, @user207421 what I meant was that this code will fail badly and would return true like it is checking for even numbers above 2 i.e 4,6,8,10 will become Prime and other odd will become Non-prime that is surely wrong

Compiling Error: Missing return statement [duplicate]

This program plays craps with 3 different methods. I need help in playing craps but i’m required to have these 3 different methods but for some reason every time I compile I am getting this error:

CrapsAnalysis.java:48: error: missing return statement > ^ 1 error Process javac exited with code 1 
public class CrapsAnalysis < public static int rollDie( int n) < return (int)(Math.random()*n) + 1 ; >public static int rollDice( ) < return rollDie(6) + rollDie(6) ; >public static boolean playOneGame( ) < int newDice = rollDice(); int roll = rollDice(); //first roll of the dice int playerPoint = 0; //player point if no win or loss on first roll if (roll == 7 || roll == 11) return true; else if (roll == 2 || roll == 3 || roll == 12) return false; else playerPoint = roll; do < if (rollDice() == 7) return false; else if (rollDice() == playerPoint) return true; else newDice = rollDice(); >while (rollDice() != playerPoint || rollDice() != 7) ; > > 

Java must look at all execution paths. What happens if the while loop ends without returning anything? You may be logically preventing that, but the Java compiler won’t do that analysis.

Provide a return statement after the end of the while loop, or throw some kind of an Exception ( IllegalStateException ?) if the code really shouldn’t ever make it there.

You can add the last return statement after your code like this:

public static boolean playOneGame() < int newDice = rollDice(); int roll = rollDice(); // first roll of the dice int playerPoint = 0; // player point if no win or loss on first roll if (roll == 7 || roll == 11) return true; else if (roll == 2 || roll == 3 || roll == 12) return false; else playerPoint = roll; do < if (rollDice() == 7) return false; else if (rollDice() == playerPoint) return true; else newDice = rollDice(); >while (rollDice() != playerPoint || rollDice() != 7); return false; > 

It will make it compile and your code will still work.

you only return statements are inside the body of an if block.

The compiler doesn’t know if any of those if blocks will ever be reached, so it’s giving you an error.

You might want to have a default return statement at the end

 > while (rollDice() != playerPoint || rollDice() != 7) ; return false; > 

I’m assuming that if that default return statement ever actually gets executed, than it’s an error state, and you should react accordingly.

You are missing a return in your while block:

public static boolean playOneGame( ) < int newDice = rollDice(); int roll = rollDice(); //first roll of the dice int playerPoint = 0; //player point if no win or loss on first roll if (roll == 7 || roll == 11) return true; else if (roll == 2 || roll == 3 || roll == 12) return false; else playerPoint = roll; do < if (rollDice() == 7) return false; else if (rollDice() == playerPoint) return true; else newDice = rollDice(); >while (rollDice() != playerPoint || rollDice() != 7) **// You are missing a return statement here.**; 

Java — Missing return statement error in a method, return null statement: stop execution of block, the null value is returned to the previous stack frame (7. in code) execution of the method that called continues with returned value; As you see, in successful case, the return null; statement, even though it is after the «real return», doesn’t influence the returned …

Источник

Оператор return в Java

Java-университет

Оператор return в Java - 1

Как мы знаем, язык Java является объектно-ориентированным языком программирования. То есть базовая концепция, т.к. сказать основа основ, заключается в том, что всё есть объект. Объекты описываются при помощи классов. В свою очередь у классов есть состояние и поведение. Например, банковский счёт может иметь состояние в виде количестве денег на счету и иметь поведения увеличение и уменьшение баланса. Поведение в Java реализуется при помощи методов. То, каким образом описывать методы, приводится в самом начале пути изучения Java. Например, в официальном tutorial от Oracle: «Defining Methods». Тут можно выделить два важных аспекта:

  • Каждый метод имеет сигнатуру. Сигнатура состоит из имени метода и его входных параметров;
  • Для методов должно быть указан тип возвращаемого значения (return type);
  • Тип возвращаемого значения не входит в сигнатуру метода.

Опять же, это следствие того, что Java язык строго типизированный и компилятор хочет заранее понимать, какие типы и где используются на столько, на сколько это возможно. Опять же, чтобы уберечь нас от ошибок. В общем, всё во благо. Ну и нам это лишний раз прививает культуру обращения с данными, как мне кажется. Итак, для методов указывается тип значения. А чтобы вернуть это самое значение из методов используется ключевое слово return .

Ключевое слово оператор return в Java

Ключевое слово оператор return относится к выражениям «управления ходом выполнения», о чём указано в oracle tutorial «Control Flow Statements». О том, как нужно возвращать значения можно так же прочитать в официальном tutorial: «Returning a Value from a Method». Компилятор тщательно следит, на сколько у него хватает сил, за тем, чтобы возвращаемое из метода значение соответствовало указанному у метода типу возвращаемого значения. Воспользуемся для примера Online IDE от tutorialspoint. Посмотрим на изначальный пример:

Как мы видим, здесь выполняется main метод, который является точкой входа в программу. Строчки кода выполняются сверху вниз. Наш main метод не может возвращать значения, иначе мы получим ошибку: « Error: Main method must return a value of type void ». Поэтому, метод просто выполнит вывод на экран. Давайте теперь вынесем получение строки в отдельный метод получения сообщения:

 public class HelloWorld < public static void main(String []args) < System.out.println(getHelloMessage()); >public static String getHelloMessage() < return "Hello World"; >> 

Как мы видим, при помощи ключевого слова return мы указали возвращаемое значение, которое использовали далее в методе println . В описании (определении) метода getHelloMessage мы указали, что он вернёт нам String . Это позволяет компилятору проверить, что действия метода согласуются с тем, каким образом он объявлен. Естественно, тип возвращаемого значения, указанного в определении метода, может быть более широким чем тип возвращаемого из кода значения, т.е. главное чтобы типы приводились друг к другу. В противном случае мы получим ошибку во время компиляции: « error: incompatible types ». Кстати, наверно сразу появился вопрос: Почему return относится к операторам управления ходом выполнения программы. А потому, что он может нарушать обычный ход выполнения программы «сверху вниз». Например:

 public class HelloWorld < public static void main(String []args)< if (args.length == 0) < return; >for (String arg : args) < System.out.println(arg); >> > 

Как видно из примера, мы прерываем выполнение метода main в том случае, если java программа наша вызвана без параметров. Важно помнить, что если у вас после return есть код, он становится недоступным. И это заметит наш умный компилятор и не даст вам запустить такую программу. Например, данный код не скомпилируется:

 public static void main(String []args)

Есть один «грязный хак» для обхода такого. Например, для целей отладки или ещё почему-то. Выше указанный код можно починить обернув return в if блок:

Оператор Return при обработке ошибок

Есть одно очень хитрое обстоятельство – мы можем использовать return совместно с обработкой ошибок. Сразу хочется сказать, что использование return в catch блоке это очень и очень плохой тон, поэтому стоит этого избегать. Но нам ведь нужен пример? Вот он:

 public class HelloWorld < public static void main(String []args) < System.out.println("Value is: " + getIntValue()); >public static int getIntValue() < int value = 1; try < System.out.println("Something terrible happens"); throw new Exception(); >catch (Exception e) < System.out.println("Catched value: " + value); return value; >finally < value++; System.out.println("New value: " + value); >> > 

На первый взгляд кажется, что должно вернуться 2, ведь finally выполняется всегда. Но нет, значение будет 1, а изменение переменной в finally будет проигнорировано. Более того, если бы value содержала бы объект и мы в finally сказали бы value = null , то из catch вернулась бы всё равно ссылка на объект, а не null . А вот из блока finally оператор return сработал бы правильно. Коллеги за такой подарок явно не скажут спасибо.

void.class

Ну и напоследок. Можно написать странную конструкцию вида void.class . Казалось бы, зачем и в чём смысл? На самом деле, в различных фрэймворках и хитрых случаях, когда используется Java Reflection API, это может очень понадобится. Например, можно проверять, какой тип возвращает метод:

 import java.lang.reflect.Method; public class HelloWorld < public void getVoidValue() < >public static void main(String[] args) < for (Method method : HelloWorld.class.getDeclaredMethods()) < System.out.println(method.getReturnType() == void.class); >> > 

Это может быть полезно в тестовых фрэймворках, где необходимо подменять реальный код методов. Но для этого нужно понимать, как этот метод себя ведёт (т.е. какие типы возвращает). Есть ещё второй способ реализации метода main из кода выше:

 public static void main (String[] args) < for (Method method : HelloWorld.class.getDeclaredMethods()) < System.out.println(method.getReturnType() == Void.TYPE); >> 

Довольно интересное обсуждение разницы между ними можно прочитать на stackoverflow: What is the difference between java.lang.Void and void? #Viacheslav

Источник

Оцените статью