首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CodeEval挑战Fizz Buzz

CodeEval挑战Fizz Buzz
EN

Stack Overflow用户
提问于 2015-11-22 20:02:10
回答 1查看 508关注 0票数 1

我正在努力学习Java。有一天,我看到一个网站提供了解决在线问题的挑战。下面是我选择的代码项目:嗡嗡声

这就是我参与这个项目的地方:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.NoSuchElementException;

public class Main {

public static void main(String[] args) throws IOException {
    File file = new File(args[0]);
    openFile(file);
    int[] line = new int[3];
    while (nextLine()) {
          try{


        line = readLine();
        String output = getLineOutput(line);
        System.out.println(output);
        }catch(NoSuchElementException e) { System.out.println("No such element exception"); }
    } 

}

static Scanner scan;

static void openFile(File file) {
    try {
        scan = new Scanner((file));

    } catch (FileNotFoundException e) {
        System.out.println("Could not find file");
    }
}

static int[] readLine() {

    int a = scan.nextInt();

    int b = scan.nextInt();

    int c = scan.nextInt();

    int[] line;
    line = new int[] { a, b, c };

    return line;

}

static boolean nextLine() {
    return scan.hasNextLine();
}

static String getLineOutput(int[] line) {
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= line[2]; i++)
        if (i % line[0] == 0 && i % line[1] == 0) {
            sb.append("FB ");
        } else {
            if (i % line[0] == 0) {

                sb.append("F ");
            }
            if (i % line[1] == 0) {
                sb.append("B ");
            }
            if (i % line[0] > 0 && i % line[1] > 0) {
                sb.append(i + " ");
            }

        }
    return sb.toString();
}

}

当我在命令提示符下运行程序时,作为第一个参数,我的程序似乎可以提供一个文本文件的路径。在CodeEval上,我得到以下错误:

CodeEval错误:10秒后编译被中止

我应该以不同的方式访问文件吗?我有什么例外吗?我的任何一个例外都没有激励我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-22 20:52:02

如果这对将来的任何人有帮助的话,这段代码不会关闭扫描器。不幸的是,在CodeEval上,如果是这样的话,代码就不会执行。

在主方法的末尾添加scan.close() (同时循环解决后)问题。

编辑:代码差异

代码语言:javascript
复制
public static void main(String[] args) throws IOException {
    File file = new File(args[0]);
    openFile(file);
    int[] line = new int[3];
    while (nextLine()) {
          try{   
        line = readLine();
        String output = getLineOutput(line);
        System.out.println(output);
        }catch(NoSuchElementException e) { System.out.println("No such element exception"); }
    } 
    scan.close();

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33859511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档