我是一个Java初学者。现在,我尝试修复代码中的错误。据说有3个错误:else without if。我一直在改变我的代码,但看起来我会有更多的其他错误。
我编写了一个程序,询问用户的姓氏,询问他们在点名过程中必须等待多长时间,并且我需要使用else if来使只打印一条语句。
import java.util.Scanner;
public class CompareTo
{public static void main( String[] args )
{ Scanner Keyboard = new Scanner (System.in);
String Name, Carswell, Jones, Smith, Young;
System.print.out( "What's your last name? ");
Name = Keyboard.next();
"Name".compareTo("Carswell");
if ( "Name" < "Carswell" )
{System.out.print( "You dont' have to wait long, " + Name);
}
"Name".compareTo("Jones");
else if ( "Name" > "Carswell" && Name < "Jones" )
{System.out.print( "that's not bad, " + Name );
}
"Name".compareTo("Smith");
else if ( "Name" > "Jones" && Name < "Smith")
{System.out.print( "looks like a bit of a wait, " + Name );
}
"Young".compareTo("Young");
else if ( "Name" > "Smith" && Name < "Young" )
{System.out.print( "it's gonna be a while, " + Name );
}
else
{System.out.print( "not going anywhere for a while, " + Name );
}
}
}发布于 2015-02-15 14:25:32
问题出在这里:
if ( "Name" < "Carswell" )
{System.out.print( "You dont' have to wait long, " + Name);
}
"Name".compareTo("Jones"); //This is the issue
else if ( "Name" > "Carswell" && Name < "Jones" )
{System.out.print( "that's not bad, " + Name );
}if和else if之间有"Name".compareTo("Jones");。if和else if之间不应该有任何代码。将上面的代码移动到if块或else if块以编译您的代码。
发布于 2015-02-15 14:36:28
您的代码有很多错误,但正如您所说的,您得到的是else,如果没有if,那么请考虑以下内容
import java.util.Scanner;类CompareTo{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String Name, Carswell, Jones, Smith, Young;
System.out.println( "What's your last name? ");
Name = keyboard.next();
if ( Name.compareTo("Carswell")<0 )
{
System.out.print( "You dont' have to wait long, " + Name);
}
/*
if you have an else if after if; then between them
you cannot write any other code
because you cant write an else if without an if
thats why you getting error
*/
else if(Name.compareTo("Carswell") > 0 && Name.compareTo("Jones")<0){
System.out.print( "that's not bad, " + Name );
}
}}
发布于 2015-02-15 14:42:26
//千万不要使用java预定义的方法作为类名
//变量必须以小写字母开头
public class TestClass{
public static void main( String[] args )
{
Scanner Keyboard = new Scanner (System.in);
String Name, Carswell, Jones, Smith, Young;
System.out.print( "What's your last name? ");
Name = Keyboard.next();
if (Name.compareTo("Carswell")<0){
System.out.print( "You dont' have to wait long, " + Name);
}
//You need to use || not &&
else if (Name.compareTo("Carswell")>0 || Name.compareTo("Jones")<0 ) {
System.out.print( "that's not bad, " + Name );
}
else if (Name.compareTo("Jones")>0 || Name.compareTo("Smith")<0)
{
System.out.print( "looks like a bit of a wait, " + Name );
}
else if ( Name.compareTo("Smith")>0 || Name.compareTo("Young")<0){
System.out.print( "it's gonna be a while, " + Name );
}
else {
System.out.print( "not going anywhere for a while, " + Name );
}
}
}https://stackoverflow.com/questions/28523576
复制相似问题