Here is an example of a simple stock program written in Java:
public class Stock {
private String name;
private int quantity;
private double price;
public Stock(String name, int quantity, double price) {
this.name = name;
this.quantity = quantity;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getValue() {
return quantity * price;
}
public void buy(int quantity, double price) {
this.quantity += quantity;
this.price = (this.price * this.quantity + price * quantity) / (this.quantity + quantity);
}
public void sell(int quantity) {
if (this.quantity < quantity) {
throw new IllegalArgumentException("Cannot sell more stocks than you have");
}
this.quantity -= quantity;
}
public String toString() {
return "Stock [name=" + name + ", quantity=" + quantity + ", price=" + price + "]";
}
}
To compile and run this program, you can use an online Java compiler such as https://www.tutorialspoint.com/compile_java_online.php. Simply copy and paste the code into the editor, and click the “Compile” button to compile it. If there are no errors, you can then click the “Execute” button to run the program.
You can also use a local Java development environment such as Eclipse or IntelliJ to write, compile, and run Java programs. These IDEs provide a more feature-rich development experience, including syntax highlighting, error checking, and debugging tools.