【问题标题】:If statement isn't taking my string values and evaluating them as a boolean (java beginner problems) [closed]如果语句没有采用我的字符串值并将它们评估为布尔值(java初学者问题)[关闭]
【发布时间】:2013-11-13 00:07:19
【问题描述】:

//程序总是打印写在 if 语句中的行。 //另外,每次我尝试添加else语句时,eclipse都会返回一个错误

import java.util.Scanner;
import java.util.Arrays;
public class Practice {

public static void main(String[] args)


Scanner input = new Scanner(System.in);
System.out.println("Enter the number of artists you would like to search: ");
int number = input.nextInt();
String junk = input.nextLine();
String []artist = new String[number];

for(int i=0; i < number ; i++)
{
    artist[i]= input.nextLine();
}
System.out.println("Here is the list of artists you searched for: " + Arrays.toString(artist) + ". Is this correct?");

String check = input.nextLine();
if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false); //this continually returns both print statements in and out of the if statement even if I input something other than yes or y and I have no idea why
{
    System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
} 

System.out.println("Please try again! Sorry for the inconvenience!"); //won't let me add an else statement

【问题讨论】:

  • 天啊。我花了过去一个小时试图弄清楚这件事,罪魁祸首是一个分号。 (以及我缺乏勤奋)非常感谢!

标签: java string if-statement boolean


【解决方案1】:

你的条件结束时有一个悬空的;

if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false) // ; was here
{

}

删除它。这被称为空语句。您可以将其重写为

if((check.equalsIgnoreCase("yes") || check.equalsIgnoreCase("y")) == false)
    ; 

{
    System.out.println("Cool! Enjoy your search!"); //this always prints no matter what
} 

由于块{ /* ... */ }是有效代码,无论如何都会被执行。

【讨论】:

    【解决方案2】:

    您的“if-then”语句被视为常规结束语句,因为有一个分号“;”在“if-then”块“{}”的范围开始之前添加。

    Oracle 表示在开始编写语句主体之前,请使用括号

    int choice = input.nextInt();  //How does the steak taste?
    
    if(choice == 1) {
    String Steak = "Amazing"
    System.out.println(choice);
    }
    

    变量“choice”以分号结尾,现在声明为用户将输入的值。由于 if-then 语句未在标头之后完成,因此可以执行包含主体和进一步语句(每个以分号结尾)的括号。

    【讨论】:

      猜你喜欢
      • 2013-11-11
      • 2013-09-04
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      相关资源
      最近更新 更多