每次我尝试编译我的代码时,都会收到关于缺少return语句的错误。关于我的代码有什么问题的任何想法?
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
所以我修复了几件事,但是现在我遇到了一个错误,其中我的变量“结果”可能尚未初始化,有什么建议吗?
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;
}
最佳答案
您需要在for
循环后放置return语句,并返回默认的char或null,以防不输入循环。并且在您的isPerfect
中,甚至可能没有输入if。
对于您的variable 'result' might not have been initialized
问题,问题在于该行:
int result,z,y = 1;
只有
y
变量被初始化为1。由于您可能未进入while循环,所以return语句将返回result
且未初始化,因此您需要为其明确指定一个值(空或其他值)整数)。如果希望它们全部为1,则可以执行以下操作:
int result,z,y;
result = z = y = 1;