【问题标题】:If else error I don't understand this errorIf else error 我不明白这个错误
【发布时间】:2015-05-01 09:04:14
【问题描述】:

我不明白这个错误是逻辑错误还是其他什么这里是编码“这个程序应该将里亚尔转换为用户使用多路 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

【问题讨论】:

  • 郑重声明,我不觉得你真的试图自己解决这个错误,你不应该得到那么多答案。尤其是那些顶级用户。
  • 你遇到了什么错误?
  • @Md.NasirUddinBhuiyan:错误信息在问题的最后。
  • 你应该学习 if-else 语句的基础知识。要在 if else 中使用多个语句,您必须在 if 条件下用 {} 覆盖该语句。

标签: java if-statement logic


【解决方案1】:

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

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 将应用的缩进将向您展示实际上是如何理解的......

【讨论】:

  • 感谢大家的回复,在我发布问题之前我已经添加了块{},并且出现了相同的错误消息,所以我按照书中的示例进行操作。我可能会错误地错过一些东西
  • @SaraAlbuainain:你为什么不发布导致问题的实际代码呢?添加大括号(在您的代码中的任何地方,而不仅仅是在我给出的示例中)确实解决了问题 - 它确实......
【解决方案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】:

    ifelse 和其他流控制语句在它们后面的 one 语句上运行。当你有多个时,你使用一个块({}):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 2011-11-19
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多