Java布尔值始终为true [英] Java boolean value is always true

查看:48
本文介绍了Java布尔值始终为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用学校的Java代码时遇到了麻烦-我试图创建一个采用布尔值的构造函数,然后在以后使用它,但是出于某种原因,它始终是正确的.有人可以告诉我我在做什么错吗?

I'm having trouble with my school Java code - I'm trying to create a constructor that takes a boolean value, and then uses it later, but for some reason it's always true. Could anyone tell me what I'm doing wrong?

我正在发布我的整个代码,我想稍微编辑一下可以使我的问题更加清楚,但是看来这只会造成混乱.

I'm posting my entire code, I thought redacting it a little would make my problem clearer, but it seems it only created confusion.

        import java.util.*;
public class L3_Z6 {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    class FunnyString{
        private boolean ascii;
        private String slowo;
        private char separator;


        public FunnyString (String slowo, char separator, boolean ascii){
            this.slowo=slowo;
            this.separator=separator;
            this.ascii=ascii;

        }
        public FunnyString (String slowo, char separator){
            this(slowo, separator, false);
        }
        public FunnyString (String slowo, boolean ascii){
            this(slowo,'-', ascii);
        }
        public FunnyString (String slowo){
            this(slowo,'-', false);
        }
        public void setAscii (boolean a){
            ascii=a;
        }
        public void setChar (char b){
            separator=b;
        }

        public String toString (){

            int dlugosc = slowo.length();
            int licznik = 0;
            String wynik="";
            do{
                if(ascii=false){
                wynik+=slowo.charAt(licznik);
                }
                if(ascii=true){
                    wynik+=(int)slowo.charAt(licznik);
                }
                if(licznik!=dlugosc-1)
                    wynik+=separator;
                licznik++;
            }while (licznik!=dlugosc);
            wynik+="\n";

            return wynik;
        }
    }
          FunnyString w1=new FunnyString("Kaktus");
          FunnyString w2=new FunnyString("Eukaliptus",'*');  
          FunnyString w3=new FunnyString("Yuka",true);

          System.out.println(w1);

          System.out.println(w2);

          System.out.println(w3);

          w1.setAscii(true);
          w1.setChar('*');
          System.out.println(w1);

          w3.setAscii(false);
          w3.setChar('!');
          System.out.println(w3);



}


}

推荐答案

在您的 if 条件下,您使用分配而不是比较.

In your if conditions, you're using assignment instead of comparison.

更改此

if(ascii=false){
    wynik+=slowo.charAt(licznik);
}
if(ascii=true){
    wynik+=(int)slowo.charAt(licznik);
}

对此

if(ascii==false){
    wynik+=slowo.charAt(licznik);
}
if(ascii==true){
    wynik+=(int)slowo.charAt(licznik);
}

这篇关于Java布尔值始终为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆