如果错误我不明白这个错误

时间:2015-05-01 09:04:15

标签: java if-statement logic

我不明白这个错误是逻辑错误还是其他什么东西就是编码"此程序应将riyal转换为用户使用多路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 个答案:

答案 0 :(得分:3)

您没有标记开始和结束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将应用的缩进将向您显示实际被理解的内容......

答案 1 :(得分:1)

如果你的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无关。

答案 2 :(得分:1)

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

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