簡體   English   中英

Java 方法在返回值之前一直運行

[英]Java method keeps running before returning value

我試圖讓我的程序在運行完最后一個 for 循環后返回該值,但由於某種原因,它在 for 循環后多次循環返回。 我在返回之前添加了一個 System.print 來測試發生了什么,它循環了很多次。 第一個結果是我所期望的,但循環導致它不正確。 我怎樣才能阻止這種情況發生?

import java.lang.Math; 
import java.util.Scanner;

public class RussianExpo 
{
    static int counter = 0;
    static int[] intArray = new int[25];
    static int value = 1;

    public static int expomod(int a, int b, int n)
    {
        while(true)
        {
            if (b == 0)
            {
                intArray[counter] = 1;
                break;
            }
            if (b==1)
            {
                intArray[counter] = a;
                break;
            }

            if (b>1)
            {
                if((b & 1) == 0); 
                {
                    intArray[counter] = 1;
                    a = (a*a);
                    b = (int) Math.floor(b/2);
                    counter++;
                    expomod(a,b,n);
                }
                if((b & 1) == 1);
                {
                    intArray[counter] = a;
                    a = (a*a);
                    b = (int) Math.floor(b/2);
                    counter++;
                    expomod(a,b,n);
                }
            }
        }

        for (int i = 0; i < 25; i++)  
        {
            if(intArray[i]>0)
            {
                value = value*intArray[i];
                value = value % n;
            }
        }
        System.out.println(value);
        return value; 
    }

    public static void main(String[] args) 
    {
        Scanner SC = new Scanner(System.in);
        System.out.println("Enter a");
        int a = SC.nextInt();
        System.out.println("Enter b");
        int b = SC.nextInt();
        System.out.println("Enter n");
        int n = SC.nextInt();

        System.out.println(expomod(a,b,n));

        SC.close();
    }

}

輸出:

Enter a
30
Enter b
2
Enter n
35

25
30
15
15

如何在 for 循環中設置中斷以退出循環? value = value % n;之后設置中斷value = value % n;

可能是錯的,我不確定該程序的意圖是什么,但我認為您的問題是遞歸調用

 if((b & 1) == 1);
                {
                    intArray[counter] = a;
                    a = (a*a);
                    b = (int) Math.floor(b/2);
                    counter++;
                    expomod(a,b,n); //This recalls the function!
                }

如果第一個值是正確的,那么它似乎是函數運行完成后的答案,后續值來自返回,因為堆棧從遞歸調用中返回,刪除了 expomod(a,b,n) 調用從 expomod() 函數內部可以解決這個問題。

簡短的回答:

從 expomod() 內部刪除對 expomod(a,b,n) 的任何調用,看看是否得到了想要的結果。

暫無
暫無

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

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