gpt4 book ai didi

java - 从同一类中的另一个方法打印值

转载 作者:行者123 更新时间:2023-12-01 22:15:18 27 4
gpt4 key购买 nike

我现在有这段代码,它可以打印整数是否为正/负、奇/偶、质/合。我只想在调用 kCheck 方法后将 kctr 的值打印到打印函数中。 for 循环是正确的,但调用 kCheck 后它只打印 0。

import javax.swing.JOptionPane;

public class FirstClass
{

public int kCheck(int num, int k, int kctr)
{
for(int l=1;l<num+1;l++){
if(( num%l) == 0){
kctr++;
//System.out.println("" +kctr); Just to check if the loop is corrrect
}
}
return kctr;
}

public static void main (String args[])
{
CheckClass checker = new CheckClass();
FirstClass checker2 = new FirstClass();
int num = 0;
int even = 0;
int odd = 0;
int negeven = 0;
int negodd = 0;
int k = 0;
int kctr = 0;
num = Integer.parseInt(JOptionPane.showInputDialog (null, "Input an integer.", JOptionPane.QUESTION_MESSAGE));

boolean ch=true;

while(ch){
if(num%2 == 0 && num>0){
ch=false;
even = 1;
}
else if(num%2 == 1 && num>0){
checker2.kCheck(num, k, kctr);
odd = 1;
System.out.println("" +kctr); /*Just to check if the loop is correct and the problem is here.
It prints the value of kctr on the method kCheck but when it comes to here, it prints 0.*/
}
else if(num%2 == 0 && num < 0){
negeven = 1;
}
else if(num%2 == 1 && num < 0){
negodd = 1;
}
break;
}

if(even == 1){
checker.posEvenCheck(num);
}
if(odd == 1){
checker.posOddCheck(num, kctr);
}
if(negeven == 1){
checker.negEvenCheck(num);
}
if(negodd == 1){
checker.negOddCheck(num);
}
}
}

最佳答案

更改这部分代码:

else if(num%2 == 1 && num>0){
checker2.kCheck(num, k, kctr);
odd = 1;
System.out.println("" +kctr); /*Just to check if the loop is correct and the problem is here.
It prints the value of kctr on the method kCheck but when it comes to here, it prints 0.*/
}

致:

else if(num%2 == 1 && num>0){
kctr = checker2.kCheck(num, k, kctr); // <- Assign the return value of the method to kctr
odd = 1;
System.out.println("" +kctr);
}

关于java - 从同一类中的另一个方法打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31201642/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com