程序的目的是计算简单股票市场交易中的收益和/或损失,最后需要显示以下信息;股份数量、购买金额、出售金额、支付的交易费用和净利润。这是我迄今为止写的代码:
public class StockTransaction {
public static void main(String[]args) {
String name;
int numberShares;
double buyPrice,sellPrice;
Scanner input = new Scanner(System.in);
System.out.print("What's your name?");
name=input.nextLine();
System.out.print("How many shares bought?");
numberShares=input.nextInt();
System.out.print("Buy price?");
buyPrice=input.nextDouble();
System.out.print("Sale price?");
sellPrice=input.nextDouble();
input.close();
System.out.println(name + "here is the information of your stock transactions:");
System.out.println("Number of shares:" + numberShares);
System.out.println("Amount of purchase:" + buyPrice*numberShares);
System.out.println("Amount of sell:" + sellPrice*numberShares);
System.out.println("Transaction fee paid:" + 15 + 15);
System.out.println("Net profit:" + (sellPrice*numberShares-buyPrice));
}
}
在您的类中,您看到了花括号过多的副作用。为了简化,您的代码如下所示:
class StockTransaction {
public static main() {
// this is the content of the main() function
}
{
// this is where your code is.
}
}
在Java中,任何方法之外的一块卷曲支撑代码都充当实例初始化器。这意味着,当您显式创建一个对象时,例如使用以下代码:
new StockTransaction();
实例初始值设定项中的代码将与任何构造函数一起运行。这是一种方便的方式,可以运行一些初始化代码,无论用户选择用什么构造函数创建对象。
但是,您会注意到,在main()
函数之前是关键字static
。static
告诉编译器可以在没有对象实例的情况下调用该方法。它属于StockTransaction
类,而不是该类的特定实例。
当程序启动时,main()
被调用为,而没有StockTransaction
类的实例。因为没有要初始化的实例,所以没有理由调用代码。
不幸的是,所有这些都是我认为更高级的Java使用,所以如果现在没有什么意义,不要担心。。。它将在以后随着你获得更多的语言经验。
同时,要使程序运行,您所需要做的就是将代码移到main()
函数中,并去掉那些多余的大括号。它应该是这样的:
import java.util.Scanner;
public class StockTransaction
{
public static void main(String[]args) {
String name;
int numberShares;
double buyPrice,sellPrice;
Scanner input = new Scanner(System.in);
System.out.print("What's your name?");
name=input.nextLine();
System.out.print("How many shares bought?");
numberShares=input.nextInt();
System.out.print("Buy price?");
buyPrice=input.nextDouble();
System.out.print("Sale price?");
sellPrice=input.nextDouble();
input.close();
System.out.println(name + "here is the information of your stock transactions:");
System.out.println("Number of shares:" + numberShares);
System.out.println("Amount of purchase:" + buyPrice*numberShares);
System.out.println("Amount of sell:" + sellPrice*numberShares);
System.out.println("Transaction fee paid:" + 15 + 15);
System.out.println("Net profit:" + (sellPrice*numberShares-buyPrice));
}
}
对我来说很好(一些小的输出问题)
What's your name?Dave
How many shares bought?1000
Buy price?10
Sale price?5
Davehere is the information of your stock transactions:
Number of shares:1000
Amount of purchase:10000.0
Amount of sell:5000.0
Transaction fee paid:1515
Net profit:4990.0
在用户名后插入空格当把数字加在一起并用字符串连接时,需要在数字周围加括号。
更改此项:
System.out.println("Transaction fee paid:" + 15 + 15);
至:
System.out.println("Transaction fee paid:" + (15 + 15));
还可以查看关于"净利润"的行,它也有一个错误