Java程序运行但没有输出

时间:2016-11-21 21:10:54

标签: java arrays

嘿伙计们我正在研究一个项目而输出什么都没有。我已经尝试过一堆没有输出的东西,除了在支架上方移动System.out.print,它刚刚打印出无数个随机数。这是一个简短的代码,所以这里是:

import java.util.Scanner;
import java.io.IOException;
import java.io.File;

public class ACSLPrintsJR {
public static int value(int num){
int [] array = {0,16,16,8,8,4,4,2,2,1,1};
    return array[num];
}

public static void main(String[] args) throws IOException {
    int top = 1;
    int bottom = 1;
    File file = new File("ACSLPRINTSJR.IN");
    Scanner scan = new Scanner(file);
    int num = scan.nextInt();
    while (num != 0){
    num = scan.nextInt();
        if (num % 2 == 0)
            top += 1 + value(num);
        else 
            bottom += 1 + value(num);
    }       
    System.out.println(top+"/"+bottom);
scan.close();
}

}

正如我所说,没有输出,这是IN文件的内容

输入是:

  

8 7 2 0

     

0

预期输出为:

  

19/3

     

1/1

当前输出: 没有

3 个答案:

答案 0 :(得分:1)

你在这里创建了一个无限循环:

:P

您从文件中读取int num = scan.nextInt(); while (num != 0){ if (num % 2 == 0) top += 1 + value(num); else bottom += 1 + value(num); } System.out.println(top+"/"+bottom); ,如果num不为零,则循环无限运行,因为您永远不会修改while循环中num的值。我冒昧地猜测你需要说:

num

但是,我不知道您的代码的确切意图,因此这可能不是理想的方法。不过,您需要在while循环中修改int num = scan.nextInt(); do{ if (num % 2 == 0) top += 1 + value(num); else bottom += 1 + value(num); num = scan.nextInt(); }while(num != 0); System.out.println(top+"/"+bottom); ,否则您将无限循环。

答案 1 :(得分:1)

您需要在循环中读取扫描仪。以下是为您更新的代码。

public class ACSLPrintsJR {
    public static int value(int num) {
        int[] array = {0, 16, 16, 8, 8, 4, 4, 2, 2, 1, 1};
        return array[num];
    }

    public static void main(String[] args) throws IOException {
        File file = new File("ACSLPRINTSJR.IN");
        Scanner scan = new Scanner(file);
        int num;
        while (scan.hasNext()) {
            int top = 1;
            int bottom = 1;
            while ((num = scan.nextInt()) != 0) {
                if (num % 2 == 0)
                    top += value(num);
                else
                    bottom += value(num);
            }
            System.out.println(top + "/" + bottom);
        }
        scan.close();
    }
}

答案 2 :(得分:0)

num变量永远不会更改其值,我认为您必须为文件中的每一行执行此操作。您可以像while(scan.hasNextInt())一样更新您的保护,这样您就可以继续前进,直到您的文件中有一个int值,然后您使用scan.nextInt()选择它。其余的代码基本相同。我现在看到你的编辑,如果用`scan.nextInt()'选择的值。等于0你打印你需要的东西,重置你的计数器变量并继续进入循环,直到你选择文件中的最后0。我希望我足够清楚。