我的Java程序正在“跳过”语句

时间:2016-09-25 01:40:26

标签: java

我正在尝试用Java解决this problem。 (您只需要查看public static int[] findBase at the end)

import java.io.*;
import java.math.*;
public class palsquare {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    BufferedReader br = new BufferedReader(new FileReader("palsquare.in"));
    int base = Integer.parseInt(br.readLine());
    br.close();
    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("palsquare.out")));
    for(int x = 1; x < 300; x++){
        boolean dat = true;
        int[] square = findBase(base, x * x);
        System.out.println("Finished, here is the result: ");
        for(int m = 0; m < square.length; m++){
            System.out.print(square[m] + " ");
        }
        System.out.print("\n\r");
        for(int j = 0; j < square.length/2; j++){
            if(square[j] != square[square.length - 1 - j]){
                dat = false;
            }
        }
        if(dat){
            System.out.println("///////");
            int[] wow = findBase(base, x);
            for(int j = 0; j < wow.length; j++){
                pw.print(wow[j]);
            }
            pw.print(" ");
            for(int j = 0; j < square.length; j++){
                pw.print(square[j]);
            }
            pw.print("\n");
        }
    }
    pw.close();
}

public static int[] findBase(int Base, int num){
    System.out.println("Handling " + num);
    int index = 0;
    while(Math.pow(Base, index) <= num){
        index++;
    }
    System.out.println("The number of digits: " + index);
    if(index < 1){
        index = 1;
    }
    int remaining = num;
    int[] thisOne = new int[index];
    for(int i = index - 1; i <= 0; i++){
        int thisDigit = 0;
        while(Math.pow(Base, i) * thisDigit < remaining){
            thisDigit++;
        }
        thisOne[i] = thisDigit;
        System.out.println("The current digit: " + thisDigit);
        remaining = remaining - (int) Math.pow(Base, i) * thisDigit;
        System.out.println("The amount remaining: " + remaining);
    }
    return thisOne;
}

}

我的代码。

当我运行的findBase值大于Base时,findBase返回一个正确大小的数组,但它用零填充。我试图弄清楚为什么会发生这种情况,最后两个System.out.println没有运行。我也在猜测更新机制。有谁知道我的程序为什么“跳过”这么多代码?

2 个答案:

答案 0 :(得分:2)

 for(int i = index - 1; i <= 0; i++)

这应该改为:

  for(int i = index - 1; i >= 0; i--){

由于索引在上下文中显示为正整数

答案 1 :(得分:0)

for循环不正确:

for(int i = index - 1; i <= 0; i++){

看看它:您使用大于i的数字初始化1,然后立即测试它是否小于或等于零。由于它不是,所以永远不会输入for循环。并且您正在递增i

您的意思是:

for (int i=index-1; i>0; --i) {