2011-10-16 44 views
20

我一直在试图让一个时钟用户可以设置。我希望用户被问到问题,他们用“是”或“否”来回答。我已经做了的事情,如是否用户想要显示或不秒不使用此代码更改,但是当我想要的字符串来改变,这是行不通的,以及从AM到PM说当小时超过12这里是我使用的是什么:你如何检查是否字符串不等于在Java对象或其他字符串值?

System.out.println("AM or PM?"); 
    Scanner TimeOfDayQ = new Scanner(System.in); 
    TimeOfDayStringQ = TimeOfDayQ.next(); 

    if(!TimeOfDayStringQ.equals("AM") || !TimeOfDayStringQ.equals("PM")) { 
     System.out.println("Sorry, incorrect input."); 
     System.exit(1); 
    } 

    ... 

    if(Hours == 13){ 
     if (TimeOfDayStringQ.equals("AM")) { 
      TimeOfDayStringQ.equals("PM"); 
     } else { 
      TimeOfDayStringQ.equals("AM"); 
     } 
       Hours = 1; 
     } 
    } 

每次我输入任何内容时,它会提示我,我是否把AM,PM,或其他明智的,它给了我我写的错误,然后退出。当我删除的代码,终止与错误也不会字符串从AM改为PM时小时等于13.谢谢你的帮助,该程序的部分,这是大加赞赏。

+3

作为一个观察,为避免混淆,Java变量应该以小写字母开头。 –

回答

25

你的代码更改为:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in); 
TimeOfDayStringQ = TimeOfDayQ.next(); 

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <-- 
    System.out.println("Sorry, incorrect input."); 
    System.exit(1); 
} 

... 

if(Hours == 13){ 
    if (TimeOfDayStringQ.equals("AM")) { 
     TimeOfDayStringQ = "PM"; // <-- 
    } else { 
     TimeOfDayStringQ = "AM"; // <-- 
    } 
      Hours = 1; 
    } 
} 
13

你要使用& &地看到,它不等于“AM”,而不是等于“PM”

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { 
    System.out.println("Sorry, incorrect input."); 
    System.exit(1); 
} 

是明确的,你也可以做

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){ 
    System.out.println("Sorry, incorrect input."); 
    System.exit(1); 
} 

有在代码中not (one or the other)短语(记得(沉默)括号内)

+0

非常感谢。我对java很陌生,这可能是我犯了这样一个简单错误的原因。非常感谢你。 – Pillager225

1

更改||到& &所以它唯一的出口如果答案既不是“AM”,也不是“PM”。

相关问题