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

时间:2018-10-25 22:41:07

标签: java while-loop int

所以我下面的代码段-最终要做什么-是制作一棵树。我当前遇到问题的区域是让用户回答是否需要装饰。我希望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();
    }

问题结束^^^

我试图在while内使用if编写代码,并重复while直到布尔值设置为true

int tf = 0;
  while (tf != true){
    System.out.println("(y = 1 || n = 0) ");
    int decorations = s.nextInt();
    if(decorations == 1 || decorations == 0 ){
      decor = true;  
    }
  }

我可以提出一些解决建议吗?我对Java还是很陌生。谢谢你的帮助

3 个答案:

答案 0 :(得分:0)

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

您想在输入无效时继续循环。但是,如果decorations小于2且大于-1,则输入有效。所以您的测试是倒退的。

答案 1 :(得分:0)

您正在将int与布尔值进行比较的第二个代码

您需要将flag(“ 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;

答案 2 :(得分:-1)

您可以共享问题的样本输入和输出吗?

如果您想要这个:

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

这可以做到:

  int decorations = s.nextInt();
    while(decorations != 1 && decorations !=0){
       System.out.println("(y = 1 || n = 0) ");
       decorations = s.nextInt();
    }
相关问题