2016-12-06 88 views
0

import java.util.Scanner;如何將字符串更改爲Int並將其相乘

公共類predictStockMarket {

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

+0

你正在做'int x = Integer.parseInt(buyOrSell);''buyOrSell'將會是某種字符串的外觀。 – user123

+0

將「nextInt」和「nextLine」混合呼叫是不明智的。 –

回答

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的鏈接,應該有助於瞭解方法以及如何獲取輸入,如整數。

相關問題