【问题标题】:How do i get this IF statement working?我如何让这个 IF 语句起作用?
【发布时间】:2011-09-30 19:44:09
【问题描述】:

修复了很多,在 myInt 声明过程中出错,说它找不到解析方法。我已经添加了提到的导入 NetBeans,但仍然没有。这是更新的代码:

import java.util.Scanner;
import java.lang.Integer;
import java.lang.String;

public class Salary {
int salary;
int sales;

public static void main(String[] args) {
   Scanner input = new Scanner ( System.in );
   double Salary;
   Salary salary = new Salary();

   System.out.print( "Please enter the amount of items sold by the employees:");  
   String sales = input.nextLine();
   String salesArray[] = sales.split(" ");

   Integer myInt = Integer.parse(salesArray[i]);

   for(int i=0; i<salesArray.length; i++){

   System.out.print(salesArray[i] + " ");
   if (Integer.parseInt(salesArray[i]) <= 0) {
   System.out.println("Please enter a value greater than zero");}
   else {
   Salary = (myInt * 0.09) + 200; }
   }

}

}

非常感谢大家的帮助,我真的很感激。

【问题讨论】:

  • 罗伯特,你能用几句话来表达这个问题吗?那样阅读会更好
  • 你可能想要 `Integer myInt = Integer.parseInt(salesArray[i]);' inside 循环——其中变量“i”是有效的。 ;->

标签: java arrays math if-statement


【解决方案1】:

在尝试对其执行数学运算之前,您可能希望将字符串解析为整数(在本例中为小于或等于)。您不妨尝试以下方法:

import java.util.Scanner;

public class Salary {

double salary;
int sales;

public static void main(String[] args) {
   Scanner input = new Scanner ( System.in );
   Salary salary = new Salary();
   System.out.print( "Please enter the amount of items sold by the employees:");  
   String sales = input.nextLine();
   String salesArray[] = sales.split(" ");

   for(int i=0; i<salesArray.length; i++){
      Integer myInt = Integer.parse(salesArray[i]);
      System.out.print(myInt + " ");
      if (myInt <= 0) {
         System.out.println("Please enter a value greater than zero");}
      else {
         salary = (myInt * 0.09) + 200; }
      }
    }

}

您的解决方案检查了字符串是否等于整数 0,它永远不会是,因为它是一个与整数进行比较的字符串。即使您检查了salesArray[i].equals("0"),这仍然只意味着它完全等于“0”,而忽略了“000”或“0.0”等等效形式。您还在问题中表示您想要“小于或等于”关系,而不是“等于”关系。仅当字符串恰好为“0”时,才进行字符串比较。

【讨论】:

    【解决方案2】:

    salesArray 是字符串数组。 equals 方法应该带一个字符串,即:salesArray[i].equals("0")

    但正确的方法是使用Integer.parseInt(..)

    【讨论】:

      【解决方案3】:
      if (Integer.parseInt(salesArray[i]) <= 0 ) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多