此代码将不会在多个ORS(即||)上执行if语句,而且我不知道为什么,有人可以提供帮助吗? Java的新手。
if (!"A123".equals(itemNumber) || !"A55".equals(itemNumber) || !"B750".equals(itemNumber)
|| !"C650".equals(itemNumber))
{
System.out.print("\nInvalid Item. Try again. ");
System.out.print("\nEnter an item number or END to exit: ");
itemNumber = keyboard.nextLine();
}
System.out.printf("\nThank you. %s", itemNumber);
答案 0 :(得分:2)
在您的代码中,您要问“如果项目编号不等于“ A123”或“ A55”或“ B750”或“ C650”,请执行这些操作”。因此,当您输入“ A55”时,程序会检查“ A55”不等于“ A123”或“ A55”。...哦,它不等于“ A123”,因此条件为真。
如果您更改这样的要求。 “如果项目编号不等于“ A123”,“ A55”,“ B750”和“ C650”,请执行这些操作”。因此,当您输入“ A55”时,程序会检查“ A55”不等于“ A123”和“ A55” ...哦,它不等于“ A55”,因此条件为假。例子
if (!"A123".equals(itemNumber) && !"A55".equals(itemNumber) && !"B750".equals(itemNumber) && !"C650".equals(itemNumber))
{
System.out.print("\nInvalid Item. Try again. ");
System.out.print("\nEnter an item number or END to exit: ");
itemNumber = keyboard.nextLine();
}
System.out.printf("\nThank you. %s", itemNumber);
或者您可以将您的要求更改为类似的内容, “如果项目编号等于“ A123”或“ A55”或“ B750”或“ C650”,则打印“谢谢”,否则请执行这些操作。”这是正确的。例子
if ("A123".equals(itemNumber) || "A55".equals(itemNumber) || "B750".equals(itemNumber) || "C650".equals(itemNumber))
{
System.out.printf("\nThank you. %s", itemNumber);
}
else{
System.out.print("\nInvalid Item. Try again. ");
System.out.print("\nEnter an item number or END to exit: ");
itemNumber = keyboard.nextLine();
}
答案 1 :(得分:1)
您可能想使用“ AND”运算符代替“ OR”:
public MainPage()
{
this.InitializeComponent();
ObservableCollection<StudentsList> studentsLists = new ObservableCollection<StudentsList>();
studentsLists.Add(new StudentsList() { StudentName = "first student" });
studentsLists.Add(new StudentsList() { StudentName = "second student" });
studentsLists.Add(new StudentsList() { StudentName = "third student" });
studentsLists.Add(new StudentsList() { StudentName = "fourth student" });
studentsLists.Add(new StudentsList() { StudentName = "fifth student" });
_ClassRoomDetailsList.StudentsArray = studentsLists;
//assigned values to observable collection here
list1.ItemsSource = _ClassRoomDetailsList.StudentsArray;
}
public ClassRoomDetailsList _ClassRoomDetailsList = new ClassRoomDetailsList();
表示“如果if (!"A123".equals(itemNumber) && !"A55".equals(itemNumber) && !"B750".equals(itemNumber) && !"C650".equals(itemNumber))
{
System.out.print("\nInvalid Item. Try again. ");
System.out.print("\nEnter an item number or END to exit: ");
itemNumber = keyboard.nextLine();
}
System.out.printf("\nThank you. %s", itemNumber);
不等于A123并且itemNumber
不等于A55并且itemNumber
不等于B750并且itemNumber
不等于C650“
更好的方法是使用itemNumber
语句:
switch
答案 2 :(得分:1)
您的错误是您使用'或'操作。您应该对此操作使用'AND'操作。同样,如果对此问题使用Arrays.asList和contains()方法,我认为这很简单。
if (!"A123".equals(itemNumber) && !"A55".equals(itemNumber) && !"B750".equals(itemNumber) && !"C650".equals(itemNumber))
{
System.out.print("\nInvalid Item. Try again. ");
System.out.print("\nEnter an item number or END to exit: ");
itemNumber = keyboard.nextLine();
}
System.out.printf("\nThank you. %s", itemNumber);