2017-02-19 32 views
1
import java.util.Scanner; 
import static java.lang.System.*; 

public class Whativelearned { 

    enum MyfirstEnum {one, two, three} 

    public static void main(String[] args) { 
     Scanner keyboardinput = new Scanner(in); 
     MyfirstEnum trolley; 
     char a1; 

     out.println("Do you pee in the shower"? Y/N"); 
     a1 = keyboardinput.findWithinHorizon(".", 0).charAt(0); 


     if (a1=='Y'||a1=='y') { 
      trolley=MyfirstEnum.one; 
      out.println("Ewwwwwww"); 
     } 


     if (a1=='N'||a1=='n') { 
      trolley=MyfirstEnum.two; 
      out.println("Well somebody isn't being very honest"); 
     }else { 
      out.println("You're not so keen on following instructions, are you?"); 
     } 

     keyboardinput.close(); 
    } 

} 

我希望我的else语句覆盖所有的结果,除了在if案件的案件。
正如我希望它作为(!(a1=='Y'||(a1=='y'||a1=='n'||a2=='N'))我else语句似乎并没有发挥作用(JAVA)

但是当我运行它的上市else声明似乎在所有情况下被执行。

+3

你else语句是指最后'if'块只有这样,它只被触发时'(!(A1 == 'N' || A2 == 'N'))'。 –

回答

1

试试这个

if (a1=='Y' || a1=='y') { 
    trolley=MyfirstEnum.one; 
    out.println("Ewwwwwww"); 
} else if (a1=='N' || a1=='n') { 
    trolley = MyfirstEnum.two; 
    out.println("Well somebody isn't being very honest"); 
} else { 
    out.println("You're not so keen on following instructions, are you?"); 
} 
+0

与switch语句甚至更好: ' 开关(A1){ 情况下( 'Y'): 情况下( 'Y'):{ 手推车= MyfirstEnum.one; out.println(“Ewwwwwww”); 休息; } case('N'): case('n'):{ trolley = MyfirstEnum.two; (“嗯,有人不是很诚实”); 休息; } 默认:{ out.println(“你不那么热衷于遵循指示,是吗?“); } } ' –

0

else语句总是具体到一个if声明。因此,只要最后的if条件未得到满足,就会执行您的else子句。

无法比拟的条件都满足时,只执行你的条款,你需要改变你的if语句else if像这样:

if (a1 == 'y' || a1 == 'Y') { 
    // ... 
} else if (a1 == 'n' || 'a1 == 'N') { 
    // ... 
} else { 
    // .... 
} 

另一种方式来解决这将是使用switch声明。这些用于比较变量和一组常量。您可以使用它们像这样:

switch (a1) { 
    case 'y': 
    case 'Y': 
     // ... 
     break; 
    case 'n': 
    case 'N': 
     // ... 
     break; 
    default: 
     // ... 
} 

请阅读一些更多关于switch声明你尝试在其他情况之前。

0

只要写else befor第二for循环:

else if (a1=='N'||a1=='n') { 
0

代码执行是最好的预演理解。

  1. 如果你在你的代码中做了,你会发现第一个if语句被检查,如果它的值为true,那么它的相应的进程被执行。
  2. 现在控件向下移动以执行下一个if语句。此if声明检查与上述if互斥的条件。如果其为真(仅在上述情况为假时),则执行其相应的过程,如果其为假,则执行零件过程。

您需要使用之后if elseif其次是else