gpt4 book ai didi

java - 无法让 Java 使用 if 语句为变量赋值

转载 作者:行者123 更新时间:2023-12-01 23:21:12 25 4
gpt4 key购买 nike

这段代码应该从用户那里获取一个字母输入,然后根据它的点数为该字母分配一个值。这是我在 Java 中工作的第一部分,由于某种原因我无法获得 if语句为变量分配任何内容。

import java.util.Scanner;

public class LetterValues {

public static void main(String args[]){

Scanner scanner = new Scanner(System.in);
String letterInput1, letterInput2, letterInput3, letterInput4;
int firstLetter = 0, secondLetter = 0, thirdLetter = 0, fourthLetter = 0;

// Asks for first input letter
System.out.print("What is your first letter? ");

// Reads the first input letter
letterInput1 = scanner.next();

// Converts the first letter to upper case, prints out to check
System.out.println(letterInput1.toUpperCase());

// Prints out first letter to check
System.out.println(letterInput1);

// Assigns a value to the firstLetter int based on the value of letterInput1
if ( (letterInput1 == "A") || (letterInput1 == "E") )
{
firstLetter = 1;
}
else if ( (letterInput1 == "D") || (letterInput1 == "R") )
{
firstLetter = 2;
}
else if ( (letterInput1 == "B") || (letterInput1 == "M") )
{
firstLetter = 3;
}
else if ( (letterInput1 == "V") || (letterInput1 == "Y") )
{
firstLetter = 4;
}
else if ( (letterInput1 == "J") || (letterInput1 == "X") )
{
firstLetter = 8;
}
else
{
System.out.println("Error.");
}

System.out.println(firstLetter);
}
}

结果是:

    What is your first letter?  A //<--input
A
A
Error.
0
What is your second letter?

最佳答案

使用equals()比较字符串:

"A".equals(letterInput1)

关于java - 无法让 Java 使用 if 语句为变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20596624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com