Java 使循环从1计数到7
我有一个代码可以工作,但是我的for循环不能从1到7计数。基本上我需要这个循环来运行和计数1,2,3,4,5,6,7 这是我的密码:Java 使循环从1计数到7,java,loops,count,Java,Loops,Count,我有一个代码可以工作,但是我的for循环不能从1到7计数。基本上我需要这个循环来运行和计数1,2,3,4,5,6,7 这是我的密码: public class Course { public static int a; public static String code; public static int CreditHours; Course() {} Course(int newA) {a = newA;} public static int getCourse(int newA) {
public class Course {
public static int a;
public static String code;
public static int CreditHours;
Course() {}
Course(int newA) {a = newA;}
public static int getCourse(int newA) {
for (int i = 0; i <= 7; i = i + 1) {
newA = i;
a=newA;
}
return a;
我需要[7]IT2249(6),但我需要从[1]开始,然后数到[7]
这是一个学术作业。要给你一个完全准确的答案,我必须看看你是如何初始化你的类和调用getCourse(int)函数的。但至少要指出你的方向是正确的-问题是你没有循环你的打印功能是什么。您需要将for循环移到外部,并围绕getCourse(int)函数 下面是您的代码的示例:
public class Course {
public static int a;
public static String code;
public static int CreditHours;
Course() {}
Course(int newA) {a = newA;}
public static int getCourse(int newA) {
newA = i;
a=newA;
return a;
}
}
//outside your Course class, wherever your print function is in, main?
for (int i = 1; i <= 7; i = i + 1) {
int courseNumber = Course.getCourse(i)
System.out.println("["+courseNumber+"]");
}
公共课{
公共静态INTA;
公共静态字符串代码;
公共时间;
课程(){}
课程(int-newA){a=newA;}
公共静态int getCourse(int newA){
newA=i;
a=新a;
返回a;
}
}
//在你的课程之外,无论你的打印函数在哪里,main?
for(int i=1;iJavier Gonzalez让我找到了答案。我完全删除了getCourse方法,并将for循环移动到output语句
以下是修复方法:
public class Course {
public static int a;
public static String code;
public static int CreditHours;
Course() {}
Course(int newA) {a = newA;}
下面是输出语句:
public static void main(String[] args) {
System.out.println("Quenten's Copy");
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 order number");
System.out.println("The number inside the () is the credit hours");
for (int i = 1; i <= 7; i++) {
a = i;
System.out.println("[" + a + "] " + Course.getCode(code) + " (" + Course.getCreditHours(CreditHours) + ")");
}
}
}
感谢您的帮助。我不确定如何让for循环正常运行,但现在我意识到它必须在输出时运行。请标记您正在讨论的语言。在返回最终结果之前,您将遍历整个循环,结果始终为7。也许您想在for中抛出一条print语句代码>循环?i=i+1
可以简化为i++
public static void main(String[] args) {
System.out.println("Quenten's Copy");
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 order number");
System.out.println("The number inside the () is the credit hours");
for (int i = 1; i <= 7; i++) {
a = i;
System.out.println("[" + a + "] " + Course.getCode(code) + " (" + Course.getCreditHours(CreditHours) + ")");
}
}
}
course Objects each has a code (e.g. IT1006) and credit hours (e.g. 6)
The number inside the [] is the display order number
The number inside the () is the credit hours
[1] IT1006 (6)
[2] IT4782 (3)
[3] IT4789 (3)
[4] IT4079 (6)
[5] IT2230 (3)
[6] IT3345 (3)
[7] IT2249 (6)