我是编程新手,目前正在学习Java入门。我本周的作业要求我们以特定方式打印出课程列表。这是我的代码:

package u9a1_defineclassinstantiateobj;

import java.util.Scanner;

/**
 *
 * @author Staci
 */
public class U9A1_DefineClassInstantiateObj {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("Staci's Copy");

        Scanner input = new Scanner(System.in);

        String[][] courses = {
            {"IT1006", "IT4782", "IT4789", "IT4079", "IT2230", "IT3345", "IT2249"},
            {"6", "3", "3", "6", "3", "3", "6"}
        };


        System.out.println("course Objects each has a code (e.g. IT1006) and credit hours (e.g. 6)");
        System.out.println("The number inside the [] is the display number");
        System.out.println("The number inside the () is the credit hours for the course");
        for(int i = 0; i < courses[0].length; i++ )
            System.out.println("[" + (i+1) + "]" + courses[0][i] + "(" + courses[1][i] + ")");

    }

}


我需要有每行的第一门课程(IT1006),而不是每行的所有课程号,而[]和()的任何数字均未更改。我觉得这很简单,但是我无法弄清楚。感谢您的所有帮助和指导。

输出:



只能在课程编号和课程学分保持不变的情况下定义课程IT1006,而不是在输出中按行定义每个课程。

最佳答案

如果我理解您的问题,可以将courses[0][i]更改为courses[0][0]

System.out.println("[" + (i + 1) + "]" + courses[0][0] + "(" + courses[1][i] + ")");


然后将输出

Staci's Copy
course Objects each has a code (e.g. IT1006) and credit hours (e.g. 6)
The number inside the [] is the display number
The number inside the () is the credit hours for the course
[1]IT1006(6)
[2]IT1006(3)
[3]IT1006(3)
[4]IT1006(6)
[5]IT1006(3)
[6]IT1006(3)
[7]IT1006(6)


如果发现我误解了您的请求,或者为了使其更易于阅读,我发现对格式化的io进行推理更容易-我会这样做

System.out.printf("[%d]%s(%s)%n", i + 1, courses[0][0], courses[1][i]);


然后,您可以调整[](),而无需为输出变量进行额外的转义。

09-04 15:42