【问题标题】:how to use value from the for-loop outside it java如何使用外部for循环中的值java
【发布时间】:2021-06-25 14:50:38
【问题描述】:
import java.util.Scanner;
public class App {
   public static void main(String[] args) {
       double input;
       double netto=0;
       Scanner value = new Scanner(System.in);

       for(int x=0;x<4;x++){
           System.out.println("Please enter the number");
            input = value.nextInt();
           if(input>=300){
               netto= input - input*0.30;
           }
           else {
               netto =input- input*0.20;
           }
           
       }
       netto=+netto;

       System.out.println(netto);

       
   }
}

我希望代码在根据输入的值减去部分结果后添加结果。 问题是代码只保存最后一个结果并显示它。

【问题讨论】:

  • 这一行什么都不做:netto=+netto; 它只是将变量netto 的值分配给它自己。

标签: java for-loop calculation


【解决方案1】:

似乎您打算使用+= 将值累积到netto 中,而不是用= 覆盖它:

for (int x = 0; x < 4; x++) {
   System.out.println("Please enter the number");
   input = value.nextInt();
   if (input>=300) {
       netto += input - input * 0.30; // Here
   }
   else {
       netto += input - input * 0.20; // And here
   }
}

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多