有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java If-else错误我不理解这个错误

我不明白这个错误是逻辑错误还是其他什么这里是编码“这个程序应该将里亚尔转换成用户使用multiway if else选择的货币

import java.util.Scanner;

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

        double riyal, c;
        int opp;

        System.out.println("Please enter the amount of money in Riyal: ");
        riyal= kb.nextDouble();

        System.out.println("Enter the currency option(1- Dollar, 2- Euro, 3- Yen): ");
        opp= kb.nextInt();

        if(opp==1)

            c=riyal*0.267;
        System.out.print(riyal+" Riyals is converted to "+c" Dollars");

        else if (opp==2)

            c=riyal*0.197;  
            System.out.print(riyal+" Riyals is converted to "+c" Euros");

         else if (opp==3)

            c=riyal*0.27.950;
          System.out.print(riyal+" Riyals is converted to "+c" Yens");

         else
         {
            System.out.println("Invalied opption");
        }
    }
}

错误消息:

error: illegal start of expression
error: 'else' without 'if'
error: ';' expected
error: ')' expected

我正在使用的程序是Jcreator


共 (3) 个答案

  1. # 1 楼答案

    您没有标记if语句体的开始和结束-wihch意味着它们只是单个语句。您目前有效地获得了:

    if(opp==1) {
        c=riyal*0.267;
    }
    System.out.print(riyal+" Riyals is converted to "+c" Dollars");
    else if (opp==2)
    

    正如您所看到的,else不属于任何if块。我强烈建议您始终使用大括号,即使对于单个语句if体:

    if(opp==1) {
        c=riyal*0.267;
        System.out.print(riyal+" Riyals is converted to "+c" Dollars");
    } else if (opp==2) {
        ...
    } // etc
    

    请注意,如果让IDE格式化代码,这一切都会变得更加清晰。IDE将应用的缩进将向您展示如何理解事物

  2. # 2 楼答案

    如果if块包含多条语句,则应使用大括号:

    if(opp==1) {
        c=riyal*0.267;
        System.out.print(riyal+" Riyals is converted to "+c" Dollars");
    } else if (opp==2) {    
        c=riyal*0.197;  
        System.out.print(riyal+" Riyals is converted to "+c" Euros");       
    } else if (opp==3) {             
        c=riyal*0.27.950;
        System.out.print(riyal+" Riyals is converted to "+c" Yens"); 
    } ... and so on ...
    

    如果不使用大括号编写,则相当于:

    if(opp==1) {
        c=riyal*0.267;
    }
    System.out.print(riyal+" Riyals is converted to "+c" Dollars");
    
    else if (opp==2)
    

    因此else if与任何if无关

  3. # 3 楼答案

    ifelse和其他流控制语句对它们后面的语句进行操作。如果有多个块,则使用块({}):

    if(opp==1) {
        c=riyal*0.267;
        System.out.print(riyal+" Riyals is converted to "+c" Dollars");
    }
    else if (opp==2) {
    // ...