Java 为什么我的while循环被跳过?价值尚未达到

Java 为什么我的while循环被跳过?价值尚未达到,java,while-loop,int,Java,While Loop,Int,所以我下面的代码部分——它最终要做的是——创建一棵树。我目前遇到的问题是让用户回答是否需要装饰。我希望while循环继续让用户输入一个值,直到数字等于1或0。但它所做的是,它在循环之外使用“int decorations=s.nextInt();”,只是跳过了这段时间 不工作的部分是非常重要的部分,没有它我的代码将无法运行 import java.util.Scanner; class Main { public static void main(String[] args) {

所以我下面的代码部分——它最终要做的是——创建一棵树。我目前遇到的问题是让用户回答是否需要装饰。我希望while循环继续让用户输入一个值,直到数字等于1或0。但它所做的是,它在循环之外使用“int decorations=s.nextInt();”,只是跳过了这段时间

不工作的部分是非常重要的部分,没有它我的代码将无法运行

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);

/*
    __________________________________INPUTS_____________________________________
*/    

      //Tree
    System.out.println("Tree size");
    int tree = s.nextInt();
问题从这里开始

      //Decorations

    System.out.println("Decorations");
    int decorations = s.nextInt();
    System.out.println();
    while (decorations < 2 && decorations > -1){
      System.out.println("(y = 1 || n = 0) ");
      decorations = s.nextInt();
    }

我能就如何解决问题提出一些建议吗?我对java还是很陌生。感谢您的帮助

您能分享您的问题的输入和输出示例吗

如果你想要这个:

“我希望while循环继续让用户输入值,直到数字等于1或0。”

这可以做到:

  int decorations = s.nextInt();
    while(decorations != 1 && decorations !=0){
       System.out.println("(y = 1 || n = 0) ");
       decorations = s.nextInt();
    }
while(装饰<2&&decorations>-1){
System.out.println(“(y=1 | | n=0)”;
装饰=s.nextInt();
}

您希望在输入无效时保持循环。但如果
小于2且大于-1,则输入有效。因此,您的测试是反向的。

第二个代码是比较int和boolean

您需要将标志(“tf”)更改为布尔值

boolean tf = false;
while(!tf) { // by using ! we can get the oposite
 tf = decorations == 1 || decorations == 0 ? true : false;
 // do your code
}
三元是一行中的if-else,这是等效的

if(decorations == 1 || decorations == 0) 
    tf = true;
else
    tf = false;

while(装饰<2&&decorations>-1)
while(装饰==1 | |装饰==0)
相同,因此与您想要的正好相反。也许你想写
while(装饰>=2 | | |装饰1 | | |装饰<0)
或者甚至
while(装饰!=1&&decorations!=0)
?都有助于了解什么是装饰。尝试将“问题开始/结束于此”代码中的空打印更改为:System.out.println(“before-while-loop,decorations=“+decorations”);澄清问题应作为评论而不是回答。等到你有了这个(你就快到了)。在此之前,请删除此答案,以清除它给您的负面回答。@Andreas我也在根据我对问题的理解填写答案。在键入该部分时,我完全忘记了我可以使用NotEqual。谢谢@kaizen和其他人的帮助!这个循环永远不会退出。
boolean tf = false;
while(!tf) { // by using ! we can get the oposite
 tf = decorations == 1 || decorations == 0 ? true : false;
 // do your code
}
if(decorations == 1 || decorations == 0) 
    tf = true;
else
    tf = false;