0

每次我尝试编译我的代码时,我都会收到关于缺少返回语句的错误。关于我的代码有什么问题的任何想法?

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx So i fixed a couple of things, but now im getting an error where my variable 'result' might not have been initialized, any suggestions?

    import javax.swing.JOptionPane;
    import java.io.*;
    public class facts
    {
      public static void main(String[]args)
    {

    String input;
    int x;
    char y,prime,perfect;
            do{
        input = JOptionPane.showInputDialog("Enter an integer");
        x = Integer.parseInt(input);
        if(x%2==0)
                System.out.println("The integer is even - it is evenly divisible by 2");
            else
                System.out.println("The integer is not even - it is not evenly divisible by 2");
            prime = isPrime(x);     
            if(prime == 't')
                System.out.println("The integer is a prime number");
            else
                System.out.println("The integer is not a prime number");
            perfect = isPerfect(x);
            if(perfect == 't')
                System.out.println("The integer is a perfect number");
            else
                System.out.println("The integer is not a perfect number");

        input = JOptionPane.showInputDialog("Enter Y for another number, anything else to quit");
        y = input.charAt(0);
        }while(y=='Y');
            System.out.println("Good Bye");

            System.exit(0);
}            
    public static char isPrime(int x)
    {
        for(int y=2;y<x;y++)
        {
            if(x%y==0)
                return 't';
            else 
                return 'f';
        }
    }
    public static char isPerfect(int x)


 public static int triAng(int x)
{
    int result,z,y = 1;
    while(y<=x)
    {
        z=y*(y+1)/2;
        y++;
        System.out.println(z);
        result = z;
    }
    return result;
}
4

4 回答 4

2

您需要在for循环之后放置 return 语句并返回默认的 char 或 null,以防不进入循环。而在你的isPerfect,即使是 if 也可能不会被输入。

对于您的variable 'result' might not have been initialized问题,问题在于该行:

int result,z,y = 1;

只有y变量被初始化为 1。由于您可能没有进入 while 循环,因此 return 语句将result在未初始化的情况下返回,因此您需要为其显式指定一个值(null 或任何整数)。如果您希望它们全部为 1,您可以执行以下操作:

int result,z,y;
result = z = y = 1;
于 2013-05-01T19:47:50.527 回答
0

在您的方法中,对于代码未进入 if块isPerfect的情况,您没有 return 语句。if(x%y==0)

于 2013-05-01T19:48:29.553 回答
0

例如,如果 x <= 1 或 x%y 从不为 0,则此代码可能不会返回:

 public static char isPerfect(int x)
    {
        int y,z=0;
        for(y=1;y<x;y++)
        {
            if(x%y==0)
            {
                z+=y;
                if(z==x)
                    return 't';
                else
                    return 'f';
            }
        }
    }
于 2013-05-01T19:48:42.053 回答
0

isPrimeandisPerfect方法中,您的代码可能不会进入 for 循环。要对其进行调整,请在这些方法的末尾放置一个默认返回或抛出异常。

于 2013-05-01T19:48:54.927 回答