3 回答
TA贡献1828条经验 获得超4个赞
请将您的代码修改为:
public class Example {
public static void main(String[] args) {
int x = 0, n = 0, p = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your number to check even or odd: ");
x = sc.nextInt();
evenOdd(x);
System.out.println("Enter your number to make a box: ");
n = sc.nextInt();
boxMake(n);
System.out.println("Enter a number to check if prime: ");
p = sc.nextInt();
checkPrime(p);
sc.close();
}
public static void evenOdd(int x) {
if (x % 2 == 0) {
System.out.println(x + " is even.");
return;
}
System.out.println(x + " is odd.");
}
public static void boxMake(int n) {
for (int i = 0; i < n; i++) {
for (int x = 0; x < n; x++) {
System.out.print("*");
}
System.out.println("");
}
}
public static void checkPrime(int n) {
int i;
int m = 0;
int flag = 0;
m = n / 2;
if (n == 0 || n == 1) {
System.out.println(n + " is not a prime number");
} else {
for (i = 2; i <= m; i++) {
if (n % i == 0) {
System.out.println(n + " is not a prime number");
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(n + " is a prime number");
}
}
}
}
TA贡献1744条经验 获得超4个赞
n并且x是您方法中的局部变量。请记住,例如nfrom与fromevenOdd()相同,除了名称之外什么都没有。如果你想在你的类中使用并且将它们定义为类成员。nboxMake()nx
import java.util.*;
public class Method{
private int n;
private int x;
TA贡献2021条经验 获得超8个赞
使 main 方法看起来像这样,并从您的方法中删除 Scanners,如下所示:
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your number to check even or odd: ");
x = sc.nextInt();
System.out.println("Enter your number to make a box: ");
n = sc.nextInt();
System.out.println(evenOdd(x));
System.out.println(boxMake(n));
System.out.println(checkPrime(n));
}
public static boolean evenOdd(int x) {
boolean odd = false;
if(x % 2 ==0){
odd = true;
System.out.println(odd + " is true.");
}
return odd;
}
public static void boxMake(int n) {
for(int i=0; i<n; i++){
for(int x=0; x<n; x++){
System.out.print("*");
}
System.out.println("");
}
}
public static int checkPrime(int n){
int i;
int m=0;
int flag=0;
m=n/2;
if(n==0||n==1){
System.out.println(n + " is not a prime number");
}else{
for(i=2; i<=m; i++){
if(n % i == 0){
System.out.println(n + " is not a prime number");
flag = 1;
break;
}
}
if(flag == 0){
System.out.println(n + " is a prime number");
}
}
return n;
}
}
添加回答
举报