如何将字符串更改为Int并将其相乘

时间:2016-12-06 20:43:24

标签: java jgrasp

import java.util.Scanner;

公共课预测StockMarket {

public static void main(String args[]){
    int openingPrice;
    int currentPrice;
  int numberOfStocks;
    String buyOrSell;
  int buyNumber;
  int sellNumber;

    Scanner number=new Scanner(System.in);
  Scanner text=new Scanner(System.in);

    System.out.println("What is the Opening Price? ");//Asking for the opening price
    openingPrice=number.nextInt();            //storing into current price variable

    System.out.println("What is the Current Price? ");//Asking for the Current Price
    currentPrice=number.nextInt();            //storing into current price variable

    System.out.println("Do you want to buy or sell? ");//Asking if they want to buy or sell
    buyOrSell=text.nextLine();          

     if (buyOrSell.equalsIgnoreCase("buy")){
           System.out.println("How many stock do you want to buy ");//Asking the user for hours per week
        int x = Integer.parseInt(buyOrSell);
        buyNumber=number.nextLine(); 
        int i;

        i = (buyNumber*currentPrice)-(openingPrice*buyNumber);
        System.out.println(i);

      }
         else {
          System.out.println("How many stock do you want to sell");
          sellNumber=number.nextLine();

           int i;
           i = (sellNumber*currentPrice)-(openingPrice*sellNumber);
            System.out.println(i);

     }

我试图将用户想要买入或卖出的金额乘以当前价格,然后从开盘价和买入数中减去。

我遇到的问题是它没有读取用户输入并且给出了一个字符串无法转换为int

1 个答案:

答案 0 :(得分:0)

我认为你做这个时有点困惑,这应该适合你:

if (buyOrSell.equalsIgnoreCase("buy")){
    System.out.println("How many stock do you want to buy ");
    buyNumber=number.nextInt(); 
    int i = (buyNumber*currentPrice)-(openingPrice*buyNumber);
    System.out.println(i);
  }

以下是Scanner对象JavaDocs的链接,了解方法以及如何获取整数等输入应该会有所帮助。