程序在做什么

时间:2014-09-18 14:56:46

标签: java

这个程序是找不到的。可被k整除的输入。
但是我得到了一个执行此操作的程序,但无法理解标记为// <--的代码是什么。

public static void main(String[] args) throws NumberFormatException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader (System.in));

    String s = br.readLine();// <--
    int end = s.indexOf(' ');// <--
    int n = Integer.parseInt(s.substring(0, end));// <--
    int k = Integer.parseInt(s.substring(end+1));// <--

    int count = 0;

    for (int i=0; i < n; i++){
        if (Integer.parseInt(br.readLine())%k == 0){
            count++;
        }
    }
    System.out.println(count);  
}

3 个答案:

答案 0 :(得分:1)

用注释解释代码:

public class division {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String s = br.readLine(); //reads a line from the console (user has to enter with keyboard and then push [ENTER])
        int end = s.indexOf(' '); //finds the index of the first space and writes it into "end"
        int n = Integer.parseInt(s.substring(0, end)); //parses an int from the given user input. stops at the first space (because of "end")
        int k = Integer.parseInt(s.substring(end + 1)); //parses an int from the given user input. starts after the first space (because of "end")

        int count = 0;

        for (int i = 0; i < n; i++) {
            if (Integer.parseInt(br.readLine()) % k == 0) {
                count++;
            }
        }
        System.out.println(count);
    }
}

演示输入:

  1. 编译并运行程序
  2. 输入以下字符串3 4,然后按[ENTER](第一个数字确定您进行检查的频率,第二个数字确定您要检查的数字)
  3. 输入以下字符串8 12 7,然后按[ENTER](这些是您要检查的数字)
  4. 您在控制台2中得到结果(因为两个数字(8&amp; 12)可被4整除)

答案 1 :(得分:0)

 String s = br.readLine();// reads the inputstream

    int end = s.indexOf(' '); //make a integer variable and initialize it with the index of  first space in string
    int n = Integer.parseInt(s.substring(0, end)); // performs substring operation and this line stops at the first space 
    int k = Integer.parseInt(s.substring(end+1));*/ performs substring operation and stops at after the first space

答案 2 :(得分:0)

在运行程序时,您必须通过&#34; n&#34;和&#34; k&#34;由控制台上的(&#34;&#34;)空格分隔。 你的程序做的是它从控制台作为一个完整的字符串。 现在,您的注释代码将拆分此字符串并将其解析为整数。

也可以实现这一目标
String[] nums = br.readLine().split(" ");
int n = Integer.parseInt(nums[0]);
int k = Integer.parseInt(nums[1]);