簡體   English   中英

從同一類中的另一個方法打印值

[英]Printing a value from another method in the same class

我現在有這段代碼,它打印一個整數是否為正/負,奇/偶,素/復合。 我只希望在調用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM