【问题标题】:Adding if else for negative numbers为负数添加 if else
【发布时间】:2019-09-11 00:04:15
【问题描述】:

我试图添加一个 if else 语句,所以当利润为负时,它告诉他们它的利润是负的,而当它为正时,它告诉他们它是正的。我将 if else 语句放在哪里以及我将如何格式化以便它工作。

import java.util.Scanner;
class Assignment2
{
    public static void main(String[] args) //header of the main method
    {
     Scanner in = new Scanner(System.in);


        String First;
        String Last;
        String StockCode;
        double ShareNumber;
        double StockBuy;
        double StockSell;
        final double charge =.02;

        System.out.println("Enter your First name");
        First = in.nextLine();

        System.out.println("Enter your Last name");
        Last = in.nextLine();

        System.out.println("Enter the stock code");
        StockCode = in.nextLine();

        System.out.println("How much did the stocks cost?");
        StockBuy = in.nextInt();

        System.out.println("How many shares did you buy?");
        ShareNumber = in.nextInt();

        System.out.println("Customer Name:" + First.toUpperCase() + ' ' + Last.toUpperCase());

        System.out.println("Stock Code:" + StockCode );
        System.out.println("Stock Cost:" + ((StockBuy * charge) + (ShareNumber*StockBuy)));

  }
}

【问题讨论】:

    标签: java string if-statement


    【解决方案1】:

    在从用户那里获得所有变量值之后,定义一个 double 类型的变量,称为利润 = 一些基于你得到的变量的数学计算然后

    if(profit>0) {System.out.println("positive profit");}
    else if(profit<0) {System.out.println("negative profit");}
    else if(profit==0) {System.out.println("zero profit");}
    

    【讨论】:

      【解决方案2】:

      您的某些代码是否在传输过程中丢失了?最后好像有很多空白,我注意到你没有使用StockSell

      编辑:有人重新格式化了您的代码,所以空白消失了,但传输中丢失的问题仍然存在

      如果不是,您将不得不提出一些利润计算。由于利润是您可能希望在其他时间显示的关键指标,因此我将声明一个变量double profit,并将您的其他声明放在顶部附近。计算利润后,您可以将变量 profit0 进行 if-else 比较,然后放在最方便的地方。

      【讨论】:

        猜你喜欢
        • 2017-07-17
        • 1970-01-01
        • 2013-12-18
        • 2021-11-23
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        相关资源
        最近更新 更多