Java if-else条件语法错误?

时间:2015-05-10 05:31:50

标签: java

我正在尝试运行以下程序,但遇到一些错误。有人可以帮助我,理解条件陈述的错误吗?

import java.util.Scanner;


public class separatingFirstCharacters {

    public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

        System.out.println("Type your name: ");
        String name = reader.nextLine();


        If (name.length()>3) {
            char firstcharacter =name.charAt(0);
            System.out.println ("First character : " + firstcharacter );
            char secondcharacter = name.charAt(1);
            System.out.println ("Second character : " + secondcharacter );
            char thirdcharacter=name.charAt(3);
            System.out.println("Third character: "+thirdcharacter);
            }
            else
            {
                System.out.println("name : " + name);
            }
        }       
    }

控制台错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method If(boolean) is undefined for the type separatingFirstCharacters
    Syntax error, insert ";" to complete Statement
    Syntax error on token "else", delete this token

    at separatingFirstCharacters.main(separatingFirstCharacters.java:13)

5 个答案:

答案 0 :(得分:1)

Java是区分大小写的语言,if是小写的。

答案 1 :(得分:1)

你有1个编译问题('if'应该是'if')而另一个问题是第三个char是第四个(name.charAt(3)应该是name.charAt(2)):

import java.util.Scanner;

public class separatingFirstCharacters {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.println("Type your name: ");
        String name = reader.nextLine();

        if (name.length() > 3) {
            char firstcharacter = name.charAt(0);
            System.out.println("First character : " + firstcharacter);
            char secondcharacter = name.charAt(1);
            System.out.println("Second character : " + secondcharacter);
            char thirdcharacter = name.charAt(2);
            System.out.println("Third character: " + thirdcharacter);
        } else {
            System.out.println("name : " + name);
        }
    }
}

答案 2 :(得分:0)

所有java基本语法都区分大小写,小写

如果(name.length()→3)

答案 3 :(得分:0)

排队 如果(name.length()> 3){

改为 if(name.length()> 3){

请注意,如果应该用小写字母写

答案 4 :(得分:0)

请纠正他的语法... 它应该是:

if (name.length()>3) {
     char firstcharacter =name.charAt(0);
     System.out.println ("First character : " + firstcharacter );
     char secondcharacter = name.charAt(1);
     System.out.println ("Second character : " + secondcharacter );
     char thirdcharacter=name.charAt(3);
     System.out.println("Third character: "+thirdcharacter);
    }
     else
       {
         System.out.println("name : " + name);
        }
     }