【问题标题】:Print result of a loop in Java在 Java 中打印循环的结果
【发布时间】:2017-05-20 03:55:24
【问题描述】:

此代码不起作用。我收到以下似乎无法解决的错误(在 Eclipse 中):

语法错误,插入“:: IdentifierOrNew”完成ReferenceExpression
语法错误,插入“;”完成 BlockStatements
重复的局部变量兴趣

import java.util.Scanner;

public class DoWhile {

    public static void main (String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("balance: ");
        int balance = in.nextInt();
        System.out.print("interestRate: "); 
        double interestRate = in.nextDouble();
        System.out.print("year: ");
        int year = in.nextInt();

        System.out.print("input: ");
        String input = in.next();
        Integer interest = null;    //to define interest    

        do 
        { 
            double interest = balance * interestRate / 100;
            balance += interest;
            year++; // print current balance
        }
        while (input.equals("N"));
        System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
    };
}

【问题讨论】:

  • 如果你修复了缩进,就会更容易看到问题。
  • interest 必须定义为Double: Double interest = null; do { interest = balance * interestRate / 100;

标签: java java.util.scanner do-while


【解决方案1】:

变量interest被声明了两次。

这里是您的代码的稍微清理过的版本:

import java.util.Scanner;

public class DoWhile {
    public static void main (String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("balance: ");
        int balance = in.nextInt();
        System.out.print("interestRate: ");
        double interestRate = in.nextDouble();
        System.out.print("year: ");
        int year = in.nextInt();

        System.out.print("press 'N' to exit");
        String input = in.next();
        double interest = 0;    //to define interest

        do
        {
            interest = balance * interestRate / 100;
            balance += interest;
            year++; // print current balance
        }
        while (input.equals("N"));

        System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
    }
}

【讨论】:

  • 没错,修正了缩进。
猜你喜欢
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 2020-03-22
  • 2022-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多