【问题标题】:Not able to compile the JAVA program. I need output when n = 8 [closed]无法编译 JAVA 程序。当n = 8时我需要输出[关闭]
【发布时间】:2014-06-14 21:49:16
【问题描述】:

这是一个算法类,我想在 n = 8 时得到这个程序的输出

import java.io.*;  
public class Algorithm
{
    public static void main(String args[])
    {

        int i,j,n;
        String s = in.readLine();
        n = Integer.parseInt(s);
        i = 2;
        while( i<= n)
        {
             for(j=1; j<= n/2; j++)
             System.out.println(i + " "+j)
             System.out.println(i + " " +j);
             i = i+2;
        }
        for (j =0; j<= i ; j+=4)
        System.out.println(" "+j);
    }
}

【问题讨论】:

  • 你在哪里定义in
  • 我不小心写了那行两次,第一个 println 不应该在那里。代码仍然不起作用
  • @Amir,我发现这是我教授给出的代码,我正在尝试查找输出,我也不确定
  • 没有输出。它不编译。

标签: java loops output parseint


【解决方案1】:

试试这样:

import java.util.Scanner;

public class Algorithm {
    public static void main(final String args[]) {

        int i, j, n;
        final Scanner scanner = new Scanner(System.in);
        try {
            String s = scanner.nextLine();
            n = Integer.parseInt(s);
            i = 2;
            while (i <= n) {
                for (j = 1; j <= n / 2; j++) {
                    System.out.println(i + " " + j);
                }
                System.out.println(i + " " + j);
                i = i + 2;
            }
            for (j = 0; j <= i; j += 4) {
                System.out.println(" " + j);
            }
        } finally {
            scanner.close();
        }
    }
}

【讨论】:

    【解决方案2】:

    这应该可行:

    import java.io.*;  
    public class Algorithm
    {
        public static void main(String args[])
        {
    
            int i,j,n;
            BufferedReader in = null;
            try
            {
                in = new BufferedReader(new InputStreamReader(System.in));
                String s = in.readLine();
                n = Integer.parseInt(s);
                i = 2;
                while( i<= n)
                {
                     for(j=1; j<= n/2; j++)
                     System.out.println(i + " "+j)
                     System.out.println(i + " " +j);
                     i = i+2;
                }
                for (j =0; j<= i ; j+=4)
                 System.out.println(" "+j);
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                if(in != null)
                {
                    try
                    {
                        in.close();
                    }
                    catch(IOException e) {}
                }
            }
        }
    }
    

    【讨论】:

    • 感谢您的帮助。代码工作正常。
    猜你喜欢
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2022-11-19
    • 2021-05-19
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多