gpt4 book ai didi

java - CodeEval 挑战 Fizz Buzz

转载 作者:行者123 更新时间:2023-11-30 03:09:45 25 4
gpt4 key购买 nike

我正在努力学习Java。有一天,我看到一个网站提供在线解决挑战的方法。这是我选择的代码项目:Fizz Buzz

这就是我的项目:

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 秒后中止

我应该以不同的方式访问该文件吗?我缺少什么异常(exception)吗?我的异常情况都没有提示我。

最佳答案

以防万一这对将来的任何人有帮助,此代码不会关闭扫描仪。不幸的是,如果是这种情况,在 CodeEval 上代码不会执行。

在 main 方法末尾添加 scan.close() (在 while 循环解决之后)解决问题。

编辑:代码差异

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

}

关于java - CodeEval 挑战 Fizz Buzz,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33859511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com