Java If语句不更改初始化值
当通过基本toString方法显示时,我的枚举类型没有从默认的“null”值更改。当用户输入JPG、GIF等时,if语句应该识别输入的字符串对应于enum。为什么if语句不接受用户的输入并将其转换为匹配枚举Java If语句不更改初始化值,java,if-statement,Java,If Statement,当通过基本toString方法显示时,我的枚举类型没有从默认的“null”值更改。当用户输入JPG、GIF等时,if语句应该识别输入的字符串对应于enum。为什么if语句不接受用户的输入并将其转换为匹配枚举 public static void processPhotos() { String value; String size; String name; String strType; double dSize; String photogra
public static void processPhotos()
{
String value;
String size;
String name;
String strType;
double dSize;
String photographer;
int iValue = 1;
Scanner kb = new Scanner(System.in);
while(iValue>0)
{
System.out.print("Enter the Photo's name.");
name = kb.nextLine();
System.out.print ("\nEnter the Photo's type(JPG, GIF, PNG, BMP, or OTHER).");
strType = kb.nextLine();
strType = strType.toUpperCase ( );
if(strType == "JPG")
{
type = Type.JPG;
}
if(strType == "GIF")
{
type = Type.GIF;
}
if(strType == "PNG")
{
type = Type.PNG;
}
if(strType == "BMP")
{
type = Type.BMP;
}
if(strType == "OTHER")
{
type = Type.OTHER;
}
System.out.print("\nEnter the Photo's size(IN Megabytes)");
size = kb.nextLine();
dSize = Double.parseDouble (size);
System.out.print("\nEnter the Photo's Photographer");
photographer = kb.nextLine();
Photo p = new Photo(name,type,dSize,photographer);
System.out.print (p.toString());
System.out.print("\n\nEnter an integer greater than zero to continue. Enter ZERO to end.");
value = kb.nextLine();
iValue = Integer.parseInt(value);
}
}
if(strType==“JPG”)
应该是:
if(strType.equalsIgnoreCase( "JPG"))
因此,对于每个
==
将其更改为equalsIgnoreCase
或equals
您必须使用equals而不是==
type == Type.JPG // comparing references
Type.JPG.equals(type) //Compares valus
将字符串与此方法进行比较
if(strType.equals("JPG"))
然后比较两个字符串是否具有相同的值
==比较这两个字符串实际上是存储在内存中的同一个对象,而它们不是。要比较字符串,需要使用
.equals
而不是=
因此,您的代码应该是if(strType.equals(“JPG”)
您不需要对此进行切换案例/条件检查,您可以将用户输入转换为枚举,如下所示:
enum Type {
JPG, GIF, PNG;
}
public static void main(String[] args) throws Exception {
String input = "GIF";
Type type = Type.valueOf(input);
System.out.println(type);
}
你应该使用equals。这里有一条讨论你为什么要这样做的线索
==测试参考等式
.equals()
测试值是否相等。在比较两个字符串时重写对象类的equals()方法
例如:str1等于(str2) 让您的生活更轻松,并解析枚举。您不必编写那么多代码,如果枚举发生更改,也不必更改方法。此外,如果strType不是枚举中的类型,则可以选择所选内容的默认类型或执行任何其他操作
if (Enum.TryParse<Type>(strType, out type))
type = Type.OTHER
if(Enum.TryParse(strType,out-type))
type=type.OTHER
当程序员将字符串与==进行比较时,会哭。让我帮你搜索一下:lol..@MustafaGenç..让我帮你搜索一下..;)@user2909717若我的答案有帮助,那个么您可以选择我的回答,因为字符串是Object为什么要重写Object类的equals()方法?用于字符串比较的字符串类已重写equals()方法。您只需在string对象上调用它
if (Enum.TryParse<Type>(strType, out type))
type = Type.OTHER