【问题标题】:what's the difference between two codes两个代码有什么区别
【发布时间】:2014-04-20 08:46:23
【问题描述】:

我正在尝试在 spoj 上提交第二个代码,但它给出了错误的答案,但第一个被接受了,尽管我认为这两个代码的逻辑是相同的。

public class Main {
    public static void main(String[] args) throws java.lang.Exception {
        java.io.BufferedReader r = new java.io.BufferedReader(
                new java.io.InputStreamReader(System.in));
        String s;
        while (!(s = r.readLine()).startsWith("42"))
            System.out.println(s);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        if (n != 42) {
            System.out.println(n);
        }
    }
}

【问题讨论】:

  • 尝试使用42xyz作为输入字符串执行两个sn-ps
  • 这两个代码的区别在于第二个代码尝试将String转换为数字,如果字符串不是数字,可能会导致数字格式异常

标签: java import universe


【解决方案1】:

第二个代码中没有循环。使用以下输入数据尝试您的代码:

1
2
88
42
99

您的第二个代码将只处理输入的第一行(即1)。这是您的代码的工作示例:http://ideone.com/Qr1q3N

例如,您可以通过以下方式引入循环:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n;
        while ((n = Integer.parseInt(br.readLine())) != 42) {
            System.out.println(n);
        }
    }
}

在这里你可以看到这个代码:http://ideone.com/z8H4fP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2020-03-29
    • 2018-04-16
    相关资源
    最近更新 更多