Jgrasp java 26 error: class, interface, or enum expected - java

I'm working on a project for my class and every time I try to compile I get the following error in jGrasp:
Lab 1.java:26: error: class, interface, or enum expected
Module main()
^
1 error
I have tried looking for the error in my code but can't find it if anyone sees what is wrong that I'm overlooking that would very helpful and I would appreciate any corrections that would get rid of that error. The code is below so you can get a thorough look at it.
/*Problem: Rent
Analyze, design and code the following application:
It allows a user to enter the rent of a home and
calculate the first month payment. The first month
payment includes a security deposit (equal to the 2 months rent)
and the first month's rent.Display the following:
each month’s rent, amount of security deposit and the final payment.
Input
User: 1. Rent amount
Given: N/A
Processing: 1. Calculate security deposit = 1 month rent * 2
2. Calculate total first month rent =
1 month rent + security deposit
Output: 1. Price for 1 month of rent
2. Price of security deposit
3. Total for first months' rent
*/
//Design
Module main()
//Declarations
Declare Real oneMonthRent = 0.0//One month rent entered by user
Declare Real securityDeposit = 0.0//2 months worth of rent
Declare Real firstMonthRent = 0.0//Security deposit + 1 month rent
//Input
Set oneMonthRent = Call getRent()//user entered
//Processing
Set securityDeposit = Call calcDeposit(oneMonthRent)//oneMonthRent + oneMonthRent
Set firstMonthRent = Call calcFirstMonthRent(oneMonthRent, securityDeposit)//oneMonthRent + securityDeposit
//Output
Call showRentAnalysis(oneMonthRent, securityDeposit, firstMonthRent)//Displays oneMonthRent, Deposit, and total first month
End Module
//Gets monthly rent cost from user
Function Real getRent()
Declare Real nRent = 0.0//local variable
Display "Enter monthly rent "
Input nRent
Return nRent
End Function
//Calculates the Security deposit
Function Real calcDeposit(Real noneMonthRent)
Declare Real ndeposit = 0.0//local variable
Set ndeposit = noneMonthRent + noneMonthRent
Return ndeposit
End Function
//Calculates total first month rent
Function Real calcFirstMonthRent(Real noneMonthRent,Real nsecurityDeposit)
Declare Real nfirstMonthRent = 0.0//local variable
Set nfirstMonthRent = noneMonthRent + nsecurityDeposit
Return nfirstMonthRent
End Function
//Displays 1 month of rent, security deposit, and final for first month
Module showRentAnalysis(Real noneMonthRent,Real nsecurityDeposit,Real nfirstMonthRent)
Display "One month worth of rent cost ", noneMonthRent
Display "Security deposit cost ", nsecurityDeposit
Display "Total for first month of rent is ", nfirstMonthRent
End Module

public class Main {
public static void main(String[] args) {
double rent = 500.50;
double securityDeposit = rent*2;
double firstMonth = rent+securityDeposit;
System.out.println(firstMonth);
}
}

Related

Java Lab missing detail to get correct answer on Domjudge

I had a lab today, the time has already elapsed so it's not like anyone is doing my homework for me... I already got 0. The code I handed in comes back as wrong answer, the output I get seems to be the desired output. It's bugging me, I don't know where it is wrong. Can someone please help me find what's wrong? Any help would be appreciated, this is my third time using Java :)
package main;
import java.util.Scanner;
public class Lab1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int COST = 25000;
System.out.print("Enter the balance of your airmiles? ");
int airmiles = in.nextInt();
int flights = airmiles/COST;
int balance = airmiles%COST;
System.out.print("\nYou can redeem "+ flights +" short haul flights. The balance of your air miles will be "+ balance +".");
}
}
with output:
Enter the balance of your airmiles? 76876
You can redeem 3 short haul flights. The balance of your air miles will be 1876.
Couple of things might be there:
The COST is constant so it should be static and final and should not be defined in main. But this is just a personal choice. Don't know if your instructor took this into consideration while grading.
There is an extra space here : \n You can redeem. Just after the \n and before You. So if the output is matched by a program, it is most likely the case that this was leading to the wrong answer.
The output in you case will be: (Notice the extra space)
Enter the balance of your airmiles? 76876
You can redeem 3 short haul flights. The balance of your air miles will be 1876.
The code you probably needed was this:
import java.util.Scanner;
public class Lab1 {
static final int COST = 25000;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the balance of your airmiles? ");
int airmiles = in.nextInt();
int flights = airmiles/COST;
int balance = airmiles%COST;
System.out.print("\nYou can redeem "+ flights +" short haul flights. The balance of your air miles will be "+ balance +".");
}
}
The output will now be:
Enter the balance of your airmiles? 76876
You can redeem 3 short haul flights. The balance of your air miles will be 1876.
It may be good to know that the DOMjudge team manual has code templates that are sure to work. For the next version of DOMjudge, I've made it explicit there not to use any package statements.
I attended the tutorial today, and spoke with the TA and sent him my code.
I think that the only thing was wrong was package declaration at the beginning of the file, apparently I'm not supposed to have that when submitting files on domjudge...

While loops Depreciation (Help)

I am attempting to create a program that will output the value at the beginning of the year, the amount depreciated during year, and the total amount of overall depreciation for each year given in that life span. For example, if I bought an item in 2005 and its life span was 5 years, it would calculate the depreciation for that item for those 5 years.
I wasn't very sure where to start with this project and this is what I have so far. However, at this point I am stuck and now I am unsure of what to do next.
import java.util.Scanner;
public class ConnerCozineDepreciation {
public void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int item, year, cost, life, depreciationType, depreciationDuring, totalDepreciation, begPrice;
//GEt all the needed data from the user
System.out.println("What is the item");
item=keyboard.nextInt();
System.out.println("What is the year of purchase?");
year=keyboard.nextInt();
System.out.println("How much did it cost? (No decimals)");
cost=keyboard.nextInt();
System.out.println("What is the item's estimated life span in years?");
life=keyboard.nextInt();
System.out.println("What is the method of depreciation?(1 for straight line or 2 for double decline)");
depreciationType=keyboard.nextInt();
//PRints the description and other info of the item
System.out.println("Item:"+item);
System.out.println("Year of Purchase: "+year);
System.out.println("Cost of Purchase: "+cost);
System.out.println("Estimated life: "+life);
if(depreciationType ==1) {
System.out.println("Straight line");
}else{
System.out.println("Double Decline");
}
System.out.println("Year\tValue at Beginning of Year\t\t"
+"Amount Depreciated During Year\t\tTotal Depreciated at End of Year");
//Calculations of depreciations
if(depreciationType==1) {
while(year<=(year+life)){ //running only as many lines as wanted
year+=1;
//System.out.format("%-8d" + "$%-39.2d"+ "$%39.2d" + "$%42.4d%n", year, cost, depreciationDuring, totalDepreciation);
}
}else {
}
}
}
I think you're looking for decrementing the life value
while (life > 0) {
year++; life--; // as it gets more age, it has less life
}
Otherwise written as
for ( ; life > 0; life--) {
year++;
}
Based on the other conditions, you might want to try this instead, though
life -= depreciationType;

Debugger stops working

My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.

How to solve this program?

I found this Java exercise :
Create a class Sales that has TotalSales (double) , Commission (double),
Commissi onRate (double), and NoOfItems (integer).
write a java application that asks the user to enter the Total Sales and the number of items then calculates the commission and prints it out.
The commission rate should be as following:
Condition :
Less than 500, commissionRate is 0
Greater than or equal 500 or Number of Items >= 5, commission rate is 5%.
Grater than or equal 1000 or Number of items >=10, commission rate is 10%
..
I wrote this code:
Main Class :
import java.util.Scanner;
public class testSales {
public static void main(String[] args) {
Sales s1 = new Sales();
Scanner get = new Scanner(System.in);
System.out.println("Enter total Sales");
s1.totalSale = get.nextDouble();
System.out.println("Enter number of Items");
s1.NoOfItems = get.nextInt();
if(s1.totalSale < 500){
s1.commission = s1.commissionRate = 0;
}
else if(s1.totalSale >= 500 && s1.totalSale <= 999 || s1.NoOfItems >= 5 && s1.NoOfItems <=9){
s1.commission = s1.commissionRate = s1.totalSale * 5 / 100;
}else if(s1.totalSale >= 1000 || s1.NoOfItems >=10) {
s1.commission = s1.commissionRate = s1.totalSale *10/100;
}
System.out.println(s1.commission);
}
}
One problem in your code is the case where NoOfItems > 5 but totalSale < 500. For this case, the commission will incorrectly be set to 0 because the first if statement eats it.
Please try to be more specific with your question. "this doesn't work and I don't know why" is not easy to help with.
Aside from the point brought up by HedonicHedgehog, there are a few other things to consider:
The sales class only has two global variables, which corresponds to the information entered by the user. The other two fields, commission and commissionRate, are calculated values. Therefore, there is no need to create variables for them. Just add to the sales class accessor methods (getters) that return these values. For example, below is my getCommission() method:
public double getCommission()
{
return totalSales * getCommissionRate();
}
Of course, you can see this method is dependent upon the getCommissionRate() method. Because there is a gap on your requirements with total items, I am ignoring it for now:
public double getCommissionRate()
{
if (totalSales < 500)
return 0;
if(totalSales < 1000)
return .05;
else
return 0.1;
}
Alternatively, you could create a LOCAL commission variable, and set the value before returning it. It is a good programming practice to limit the scope of your variables. In this case, there is not a good reason to have a global commission or commissionRate variables.
Lastly, your test class is simplified because all you need to do is to prompt the user for the two needed fields, and it simply spits out the output because the Sales class provides the calculation needed to figure out the rest:
public static void main(String[] args)
{
Sales s1 = new Sales();
Scanner input = new Scanner(System.in);
System.out.print("Enter total Sales");
s1.setTotalSales(input.nextDouble());
System.out.print("Enter number of Items: ");
s1.setNumOfItems(input.nextInt());
System.out.printf("$%.2f", s1.getCommission());
input.close();
}
I used the printf() method to format the output string. The following is a sample run:
Enter total Sales: 503.45
Enter number of Items: 5
$25.17
Enter total Sales: 1003.67
Enter number of Items: 19
$100.37
Enter total Sales: 45.00
Enter number of Items: 19
$0.00
Remember that this example ignores the number of items because of the reasons already mentioned. Once you figure out what needs to be done to cover of the gap in the requirements, you can modify this code to do the rest. Also remember that your Sales class only requires two fields: totalSales and numOfItems. The other to components (commission, and commissionRate) are calculated; therefore, no global variable or setter methods needed. Just the two getter methods I provided.

Program not displaying everything it's supposed to

I am writing an inventory program for a book store that is comprised of two classes and multiple methods within these classes.
The method I'm having the most trouble with is my purchase() method which is supposed to interactively process a purchase, update the array after the purchase, and display totals for items sold and total amount of money made that day.
The method is supposed to follow these 10 steps:
Ask the user to enter the ISBN number of the book they'd like to purchase.
Search the array for the object that contains that ISBN.
If the ISBN isn't found in the array, display a message stating that we don't have that book.
If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock.
If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase.
If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity.
When they enter a 0 for the ISBN, the Scanner is supposed to close
Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased.
Print the updated array.
Display a count of how many books were purchased, and how much money was made from the purchase.
But as my code is written, after the Program prompts me to enter an ISBN, nothing happens, it just continually lets me enter numbers with no additional output.
Here is the code I have for this method. I'm pretty sure it's probably an issue with my loop as I'm not very good with looping. Can anyone spot what I'm doing wrong?
public static Book[] purchase(Book[] books) {
int itemsSold = 0;
double totalMade = 0;
double price;
int copies;
String isbn;
Scanner input = new Scanner(System.in);
int desiredCopies = 0;
int index;
double total = 0;
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
String desiredIsbn = input.next();
for (index = 0; index < books.length; index++) {
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() > 0) {
System.out.println("How many copies of this book would you like to purchase?");
if (!books[index].getISBN().equals(desiredIsbn))
System.out.println("We do not have that book in our inventory.");
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() == 0)
System.out.println("That book is currently out of stock.");
desiredCopies = input.nextInt();
}
if (desiredCopies > books[index].getCopies())
System.out.println("We only have " + books[index].getCopies() + "in stock. Please select another quantity: ");
desiredCopies = input.nextInt();
books[index].setCopies(books[index].getCopies() - desiredCopies);
if (input.next().equals(0))
System.out.println("Thank you for your purchase, your order total is: $" + total);
input.close();
total = books[index].getPrice() * desiredCopies;
itemsSold += desiredCopies;
totalMade += total;
System.out.print(books[index]);
System.out.println("We sold " + itemsSold + " today.");
System.out.println("We made $" + totalMade + "today.");
}
return books;
}
Any help would be greatly appreciated.
You are not matching every possible condition
Your if statements aren't covering all the possible permutations of conditions apparently.
You should use always use an if/else if/else block to make sure you cover all your conditions. Outside this there is absolutely no way for anyone to provide any actual solution with so little to go on.
Also
Scanner and StringTokenizer are two of the worst designed classes in the JDK outside Date and Calendar. They cause endless trouble for new people and are avoided by the veterans.

Categories

Resources