-4

it is show that error in the 2nd If statement why???

import java.security.SecureRandom;

public class Test 
{
   public static void main(String[] args)
   {
      System.out.println("T : " + Tfun());
   }

public static String Tfun()
{
    SecureRandom r = new SecureRandom();
    int T = 1+r.nextInt(10);


    if(T >= 1 && T <= 5)
        Integer.toString(T);
        return "Fast_Plod";

    if(T >= 6 && T <= 7)
        Integer.toString(T);
        return "Slow_Plod";
  }
}

how to fix that? what is the problem exactly?

3 Answers3

1

In this block (And the other if block):

 if(T >= 1 && T <= 5)
    Integer.toString(T);
    return "Fast_Plod";

You forgot brackets, so the return is always executed, resulting in the rest of the code in the method being dead code (code that can never be reached). Indentation means nothing in java, so you have to specify that the return statement is within the if block by surrounding it, and all the other lines that should be in the if block, with brackets. Also the lines Integer.toString(T); do nothing. Lastly, T can be a number greater than 7, so you must specify a return for this too.

To fix this simply add brackets:

if(T >= 1 && T <= 5) {
    return "Fast_Plod";
}
if(T >= 6 && T <= 7) {
    return "Slow_Plod";
}
else {
    return "";  //return what you want to return if it's > 7
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
0

To add on to GBlodgett's answer you can get away with not putting brackets around the block to be executed in an if statement if it is only one statement (only one ;). Java will execute the first statement after the if and then carry on as if the job is done.

M. Goodman
  • 141
  • 9
0
import java.security.SecureRandom;

public class Test {

    public static void main(String[] args) {
        System.out.println("T : " + Tfun());
    }

    public static String Tfun() {
        SecureRandom r = new SecureRandom();
        int T = 1+r.nextInt(10);

        if(T >= 1 && T <= 5) {
            Integer.toString(T);
            return "Fast_Plod";
        }else if(T >= 6 && T <= 7) {
            Integer.toString(T);
            return "Slow_Plod";
        }else {
            return "your return value.";
        }
    }
}
Sandy
  • 41
  • 2