Okay, so I am using Netbeans and it is driving me up a wall. I managed to get a code written and it yelled at me because it wasn't in a file named after the public class. So I changed it, and now it's still not working. There is now a "command execution failed" vs the compilation error I was getting before. I have no idea what I am missing.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Ryan_Lab3 {
public static void main(String[] args) { // Added 'public' here
try (Scanner scanner = new Scanner(System.in)) {
// Get the item cost from the user
double itemCost = getPositiveDouble(scanner, "Enter the cost of the item: $");
// Get the tax rate from the user
double taxRate = getPositiveDouble(scanner, "Enter the tax rate (as a percentage, e.g., 7.5 for 7.5%): ");
// Validate that the tax rate is not greater than 100%
if (taxRate > 100) {
System.out.println("Tax rate cannot exceed 100%. Setting tax rate to 100%.");
taxRate = 100;
}
// Convert tax rate percentage to a decimal
double taxRateDecimal = taxRate / 100.0;
// Calculate the taxes
double taxes = taxRateDecimal * itemCost;
// Calculate the total cost
double totalCost = itemCost + taxes;
// Output the results
printReceipt(itemCost, taxes, totalCost);
}
}
// Method to get a positive double value from user input
private static double getPositiveDouble(Scanner scanner, String prompt) {
double value = 0.0;
boolean validInput = false;
while (!validInput) {
System.out.print(prompt);
try {
value = scanner.nextDouble();
if (value < 0) {
System.out.println("Please enter a positive number.");
} else {
validInput = true;
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a numeric value.");
scanner.next(); // Clear the invalid input
}
}
return value;
}
// Method to print the receipt
private static void printReceipt(double itemCost, double taxes, double totalCost) {
System.out.println("\n--- Receipt ---");
System.out.printf("Item Cost: $%.2f%n", itemCost);
System.out.printf("Taxes: $%.2f%n", taxes);
System.out.printf("Total Cost: $%.2f%n", totalCost);
System.out.println("------------------");
}
}
I tried the suggestions that pop up on the sides and none of that has worked either and I just end up putting the original code.
You don't have a package statement in your first line. You can only omit it if your file is in the default package (src/main/java/Ryan_Lab3.java
). Else you need to provide a package name.
If you file resides e.g. in (src/main/java/com/ryan/test/Ryan_Lab3.java
) your first line must look like:
package com.ryan.test;