繁体   English   中英

Java程序运行但没有输出

[英]Java Program runs but gives no output

嗨,我正在做一个项目,输出什么也没有。 我已经尝试了很多方法,除了将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

电流输出:无

您在此处创建了一个无限循环:

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 ,并且如果num不为零,则循环无限期运行,因为您从不会在while循环中修改num的值。 我敢猜测您需要说:

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);

但是,我不知道您的代码的确切意图,因此这可能不是理想的方法。 但要点是,您需要在while循环中修改num ,否则将无限循环。

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

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();
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM