我无法让开关工作。我得到一个无法编译的源代码Date.java:75。此外,当程序返回结果时 - 我希望它还返回MONTH NAME DD,YYYY以及我已经拥有的MM / DD / YYYY。如果你能指出我正确的方向,我会很感激。
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class Date {
private GregorianCalendar date = null;
private String[] months = new String[]{ "january", "february", "march", "april", "may",
"june", "july", "august", "september", "october", "november", "december" };
public Date(int month, int day, int year) {
date = new GregorianCalendar(year, month-1, day);
}
public Date(String month, int day, int year) {
date = new GregorianCalendar(year, this.getMonth(month), day);
}
public Date(int dayOfYear, int year) {
date = new GregorianCalendar();
date.set(Calendar.DAY_OF_YEAR, dayOfYear);
date.set(Calendar.YEAR, year);
}
private int getMonth(String month) {
for (int i=0; i<months.length; ++i)
if (month.toLowerCase().equals(months)) //equals(months))
return i;
return 0;
}
public String toString() {
return date.get(Calendar.MONTH)+1 + "-" + date.get(Calendar.DATE) + "-" + date.get(Calendar.YEAR);
}
public static void main(String[] args) {
int mo;
int dy;
int yr;
String moo; // Month name string
boolean wrongInput = false;
do {
Scanner input = new Scanner( System.in ); // scanner to read input
wrongInput = false;
int menu = input.nextInt(); // menu selection
System.out.printf( "Enter 1 for format: MM/DD/YYYY \n");
System.out.printf( "Enter 2 for format: Month DD,YYYY \n");
System.out.printf( "Enter 3 to exit \n");
System.out.printf( "Choice:");
switch(menu)
{
case '1' : // MM/DD/YYYY UI
System.out.printf( "Enter Month (1-12): ");
mo = input.nextInt();
System.out.printf( "Enter Day of Month: ");
dy = input.nextInt();
System.out.printf( "Enter Year: ");
yr = input.nextInt();
Date a = new Date(mo, dy, yr); //chew
System.out.println(a); //spit
break;
case '2' : // Month DD,YYYY UI
System.out.printf( "Enter Month name: ");
moo = input.next();
System.out.printf( "Enter Day of Month: ");
dy = input.nextInt();
System.out.printf( "Enter Year: ");
yr = input.nextInt();
Date b = new Date(moo, dy, yr); //chew
System.out.println(b); //spit
break;
case '3' : // EOP
System.exit(0);
break;
default:
System.out.println("Invalid selection.");
wrongInput = true;
break;
}
while(wrongInput);
}
答案 0 :(得分:6)
您正在传递整数并检查字符。 1
为int
,而'1'
为java中的字符。
在您的代码menu
中,int
不是char
,因此您的案例应该是case 1:
而不是case '1':
所以改变你的switch
switch(menu){
case 1:
//Your code
break;
case 2:
//Your code
break;
//..And so on
}
现在将ASCII
个字符'1','2'..
的值与作为int
传递的menu
值进行比较,这些值显然不等于ASCII
值char '1'
为81
而82
为'2'
,因此在这种情况下完全无用。
答案 1 :(得分:3)
您正在检查字符,&#39; 1&#39;,&#39; 2&#39;等。请尝试使用该号码。 E.g。
case 1:
//do this
break;
答案 2 :(得分:1)
问题是你的switch
切换了一个整数,但你有chars来定义单个案例。 (Chars总是注明&#39;&#39;)。这不会立即引发编译错误的原因是java中的char
被保存为普通整数。你甚至可以用字符进行数学运算。因此,交换机将整数menu
与等效的整数{&1;&#39;,&#39; 2&#39;等等。这可能有效,但出于某种原因,char&#39; 0&#39; 0整数值为40(或41?)。因此,如果您将menu
设置为40(41?),则会触发case '1':
。
要避免这种情况,只需将代码从case '1':
case '2':
更改为case 1:
case 2
:等等。