我正在为类编写程序,循环似乎无法正确执行。它始终将i
的值返回为 0 。其余的代码看起来像宣传的那样工作,i
只是没有增加索引值。
public class Day {
String strDay;
private int d = 0;
private String[] Days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
String day;
public Day() {
return;
}
public Day(String strDay) {// this is my issue. I think I am going about this constructor all wrong
for (int i = 0; i < Days.length; i++) {
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
public int getDay() {
return d;
}
public void nexDay() {
int next;
if (d < 6) {
next = (this.d) + 1;
System.out.println("Next Day is :" + Days[next]);
} else {
next = 0;
System.out.println("Next Day is :" + Days[next]);
}
}
public void prevDay() {
int prev = 0;
if ((d > 0) && (d < 6)) {
prev = (this.d) - 1;
System.out.println("previous day is " + Days[prev]);
} else
System.out.println("previous day id " + Days[6]);
}
public int calcDay(int num) {
int newDay;
this.d = d + num;
newDay = this.d % 7;
System.out.println("calc day is" + Days[d]);
return newDay;
}
public void print() {
System.out.println("day is " + Days[d]);
}
public static void main(String[] args) {
String day;
Day Callmethod = new Day();
Scanner console = new Scanner(System.in);
System.out.println("enter a day of the week");
day = console.nextLine();
Callmethod.print();
Callmethod.nexDay();
Callmethod.prevDay();
Callmethod.getDay();
}
}
答案 0 :(得分:3)
好吧,这个
Day Callmethod = new Day();
正在调用你的空构造函数。不是带循环的构造函数(需要String
)。此外,Java变量以小写字母开头(Callmethod
看起来像class
)。我认为你在寻找像
Day day = new Day("SUNDAY");
此外,您的if
需要大括号或return
将被调用而不做任何事情(除非它与第一个条目匹配),如
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i])) {
d = i;
return;
}
}
答案 1 :(得分:1)
尝试改变这个:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
d = i;
return;
}
}
为此:
public Day(String strDay)/// this is my issue. I think I am going about this constructor all wrong
{
for(int i=0;i<Days.length;i++){
if (strDay.equalsIgnoreCase(Days[i]))
{
d = i;
return;
}
}
}
如果没有花括号,您的条件块将只是下一行代码。所以你的循环只运行一次