0

//程序总是打印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
4

2 回答 2

4

;在你的状态结束时你有一个悬空

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
} 

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

于 2013-11-13T00:08:13.537 回答
1

您的“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 语句未在标头之后完成,因此可以执行包含主体和进一步语句(每个以分号结尾)的括号。

于 2016-12-17T00:19:16.457 回答