I'm completely new to Java and need some help. I'm trying to add results for each attempt in a competition but I got stuck. So far I have the first part that works but without any results added and then I tried to find a way to add results while counting allowed attempts (which are different for each discipline) but without success. What would be the best way both to count attempts and to add results for each attempt?`
private void addResult() {
System.out.print("Enter the number of the participant you would like to add results for: ");
int number = scan.nextInt();
scan.nextLine();
while (number < 0) {
System.out.println("Error: must be greater than or equal to zero!");
number = scan.nextInt();
scan.nextLine();
}
System.out.print("Enter the name of the event you would like to see results for: ");
String event = scan.nextLine();
Participant p = findParticipantByNumber(number);
Event e = findEventByName(event);
if (p == null) {
System.out.println("No participant with number " + number + " found!");
} else if (e == null) {
System.out.println("No event called " + event + " found!");
} else {
System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
" from " + p.getTeam() +
" in " + e.getEventName() + ":" + " " + p.getResult() );
scan.nextLine();
Result r = new Result(e, p);
p.addResult(r);
}
}
I would store a HashMap of attempts as an instance variable in the Participant class, where the keys are Strings representing the events and the value corresponding to each key is the number of attempts so far for that event. You could call this map attemptsByEvent and have getter and setter methods for it in Participant. If you need, you can take a look at this page from TutorialsPoint about how to create and populate maps, and what they are.
You should also make a map that is accessible from within addResult() which has Strings representing the events as keys and the maximum allowed attempt for that event as the values. You could call this map attemptMaximums.
Then, you can modify your final block of code to check the number of attempts so far before adding the result. You should also increment the value in the Participant's map if you do add results for an attempt.
else {
System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
" from " + p.getTeam() +
" in " + e.getEventName() + ":" + " " + p.getResult() );
scan.nextLine();
Result r = new Result(e, p);
int attempts = p.getAttemptsByEvent().get(e);
if(attempts < attemptMaximums.get(e)){
p.addResult(r);
p.getAttemptsByEvent().put(e, attempts+1);
}
}
Related
I completed this java project for a class, but I cannot seem to fix the error I'm getting for the web software that grades it- it's called webcat. I've tried the test input the software suggests for a reference test against my solution, and my output looks exactly the same, but I still lost points for this error-
"Error in method main of class Event: Line number 2 of your output is incorrect (line numbers begin at 1). Your main method does not print the correct output when the input is "This is a short test " (input less than 26 characters) [] Line matched except underscores: Invalid Event Code_".
How can I fix this error when the expected ouput looks fine? Thanks in advance!
Code:
public class Event {
/**
* accepts coded event info, prints the info back to std output, and
actual cost and prize number.
*
* #param args Command line arguments - not used.
*/
public static void main(String[] args) {
// variables needed
String shrink, event, date, time, section, row, seat;
double price, discount, cost;
int prizeNum;
// accept input
Scanner userInput = new Scanner(System.in);
// format the numbers
DecimalFormat formatNum = new DecimalFormat("$#,##0.00");
// enter input and trim the space
System.out.print("Enter your event code: ");
shrink = userInput.nextLine().trim();
if (shrink.length() < 26) {
System.out.println();
System.out.println("Invalid Event Code");
System.out.println("Event code must have at least 26 characters.");
return;
}
// locates spot in index of code and assigns
event = shrink.substring(25, shrink.length());
date = shrink.substring(0, 8);
time = shrink.substring(8, 12);
section = shrink.substring(19, 21);
row = shrink.substring(21, 23);
seat = shrink.substring(23, 25);
price = Double.parseDouble(shrink.substring(12, 15)
+ "." + shrink.substring(15, 17));
discount = Double.parseDouble(shrink.substring(17, 19));
// calculates final cost
cost = price - (price * (discount / 100));
// random final number
prizeNum = (int) (Math.random() * 1000 + 1);
// prints the data to std output
System.out.println();
System.out.print("Event: " + event + " " + " " + " ");
System.out.print("Date: " + date.substring(0, 2) + "/"
+ date.substring(2, 4) + "/" + date.substring(4, 8) + " "
+ " " + " ");
System.out.println("Time: " + time.substring(0, 2) + ":"
+ time.substring(2, 4) + " " + " " + " ");
System.out.print("Section: " + section + " " + " " + " ");
System.out.print("Row: " + row + " " + " " + " ");
System.out.println("Seat: " + seat);
System.out.print("Price: " + formatNum.format(price) + " " + " " + " ");
// formats discount before print
formatNum.applyPattern("#.#'%'");
System.out.print("Discount: " + formatNum.format(discount) + " "
+ " " + " ");
// formats cost before print
formatNum.applyPattern("$#,##0.00");
System.out.println("Cost: " + formatNum.format(cost));
System.out.print("Prize Number: " + prizeNum);
Output:
Enter your event code: This is a short test
Invalid Event Code
Event code must have at least 26 characters.
I want to display the sum of two numbers beside the equal sign.
Scanner scan = new Scanner(System.in);
int i ;
System.out.println("enter a number: " );
i = scan.nextInt();
int a = i - 1 ;
while(a >= 1){
System.out.println(i +" + "+ a + " = " );
//i want to display the sum of two numbers beside the equal sign.
i =i + a ;
System.out.println(i);
a --;
// how can I display the answer beside the equal sign?
}
}
}
How can I display the answer beside the equal sign?
Change your first println to print.
As per your question I think you are most probably asking how we can show the sum of two numbers in the print statement.
So in your code after "=" you just need to add (i+a) this will sum the value of i and a.
System.out.println(i +" + "+ a + " = " + (i+a)).
I hope this answers your question.
System.out.println() method prints a "newline character" (\n) right after its' input.
There is another method that does not do this:
System.out.print()
You should change
System.out.println(i +" + "+ a + " = " ); to
System.out.print(i +" + "+ a + " = " ); this.
I have a "bank" program, with the following chunk of code:
private void doPayment(JTextField accountNumField, JTextField paymentField)
{
int accountNum = Integer.parseInt(accountNumField.getText());
double paymentAmt = Double.parseDouble(paymentField.getText());
String paymentProcessed = "-RECEIPT OF PAYMENT-" + "\n\n" + "Account Number:" + " " + accountObject.getAccountNum() + "Beginning Balance:" + " " + accountObject.getBegBalance()
+ "Payment Amount:" + " " + accountObject.getPaymentAmount() + "Ending Balance:" + " " + accountObject.getEndBalance();
String errorMsg = "ERROR: ACCOUNT NUMBER" + " " + "[" + accountObject.getAccountNum() + "]" + " " + "NOT FOUND. PLEASE VERIFY THAT THE ACCOUNT INFORMATION IS VALID AND CORRECT.";
if (accountsArrayList.contains(accountNum))
{
accountObject.transactionTwo(paymentAmt);
JOptionPane.showMessageDialog(null, paymentProcessed, "PAYMENT PROCESSED SUCCESSFULLY", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, errorMsg, "INVALID ACCOUNT ERROR", JOptionPane.PLAIN_MESSAGE);
}
}
In theory, after the user creates the account for the client, he/she navigates to a "Process Payment" window and enters two things: accountNum and paymentAmt then hits submit, at which point the doPayment method is called.
This method is supposed to work such that the program iterates through the accountsArrayList which contains THREE items: lastName, firstName, and accountNum. If it finds that the accountNum provided matches a prexisting accountNum in the arrayList, then the transaction is processed accordingly. If no matching accountNum can be found then it returns an error message.
At present, it just returns the error message in the else part of the if-else. I thought that the contains(item) method automatically iterates through the Arraylist. If that isn't the case, do I need an enhanced FOR-loop?
if (accountsArrayList.contains(accountNum))
accountsArrayList is a ArrayList which contains Objects of type Account.
contains returns true only if accountsArrayList contains an Object type Account given as argument. In your code, accountNum is a int
so the compiler reads it like if(Account == INTEGER)
You have to go throw each Account in your ArrayList and get it's accountNum and than compare the values.
for(int i = 0; i < accountsArrayList.size; i++){
if(accountsArrayList.get(i).accountNum == accountNum){
//success
}
else {
//error
}
}
I'm making a random creature generator, its going all nice and dandy, however when it comes to printing the results, it prints the same result 5 times. I tried some different things like using println() multiple times and do while loops, however every time I run the file I just get a bunch of the same results. "a b c d e" are strings that generate the creature
int x = 1;
do {
System.out.println(x +" " +a +" " +b +" " +c +" " +d +" " +e);
x++;
} while (x<=5);
The reason why you're getting the same answer 5 times is because your do-while loop runs 5 times without changing the 'creatures' .
System.out.println(a +" "+ b + " " + c + " " + d + " " +e);
If you remove the do-while loop you'll get the same answer only once however just in case i misunderstood your question i made a small demo of a simple way in which to get multiple random results with a for-loop,a String-array and the Random class
String[] creatures = {"Dog", "Cat", "Fish", "Monkey", "Horse"};
Random r = new Random();
for (int i = 0; i < 5; i++) {
String creature1 = creatures[r.nextInt(creatures.length)];
String creature2 = creatures[r.nextInt(creatures.length)];
String creature3 = creatures[r.nextInt(creatures.length)];
String creature4 = creatures[r.nextInt(creatures.length)];
String creature5 = creatures[r.nextInt(creatures.length)];
System.out.println(creature1 + " " + creature2 + " " + creature3
+ " " + creature4 + " " + creature5);
}
I'm having a problem with a variable not updating when its supposed to. I also am not sure where to update this variable as it does not fit into any of the if statement tests in my code. YOU MUST UNDERSTAND, that all I need fixed is where the variable peopleCompleted gets updated when the first person to enter is done. In my code you'll see where this first person is arriving, taking his place as the curServed and then being printed without being added to the queue holding everyone else who is in line. You'll notice that curServed gets changed in the serviceComplete() because it handles everyone else IN THE QUEUE. Below is my code and sameple output that is incorrect because of peopleCompleted not being updated for that first person. Basically, I really need help with knowing where to update his completion in the first place. This is a Simulation of a One Line One Queue. I am a beginner/student
CODE
public boolean arrival()
{
Customer myCust = new Customer(curTime);
if(curServed == null) // If no one being served
{
curServed = myCust; // myCust is served
peopleNoWait++;
return true;
}
else if(!q.isFull())
{
q.add(myCust);
peopleThatHadToWait++;
return true;
}
return false;
}
public Customer serviceComplete()
{
if(q.isEmpty())
{
curServed = null;
}
else
{
curServed = q.remove(); // Remove next from customer queue
peopleCompleted++;
sumOfWaitTime += getWaitTime();
}
return curServed;
}
THESE BELOW HANDLE THE SIMULATION ABOVE
private void doArrival()
{
boolean check = sim.arrival(); // Do an arrival
if(check == false)
System.out.println("Customer arrived but left immediately"
+ " because the line was full (too long) at time " +
sim.getTime() + ".");
else
System.out.println("A customer entered system at time " +
sim.getTime() + "." + " Number waiting in queue is "
+ sim.getNumWaiting() + ".");
}
private void doServiceComplete()
{
if(sim.notBeingServed() == true)
{
System.out.println("No customer is being served at the present time"
+ " of " + sim.getTime() + ".");
}
else
{
System.out.print("Customer " + sim.getCurCust().toString() +
" finished at time " + sim.getTime() + ". Number waiting" +
" is ");
System.out.println(sim.getNumWaiting() + ".");
}
sim.serviceComplete();
Methods that return the vals below
public int getNumWaiting()
{
int total = peopleThatHadToWait - peopleCompleted;
return total;
}
public int getTotalServed()
{
return peopleCompleted;
}
Sample output where error is:
Customer C1/T2 finished at time 7. Number waiting is 2. // Should be 1
Customer C2/T6 finished at time 7. Number waiting is 1. // Should be 0
Customer C3/T7 finished at time 13. Number waiting is 5. // 4
Customer C4/T7 finished at time 16. Number waiting is 4. // etc
Customer C5/T8 finished at time 16. Number waiting is 3.
Customer C6/T8 finished at time 17. Number waiting is 2.
Customer C7/T9 finished at time 17. Number waiting is 1.
The number of people served is 7. // Should be 8
The number of people served is 7. // Should be 8
COMMENTS:
These are the lines causing issue. The number waiting and the number of people
served are the ones that are incorrect. It is because of the the lack of the
peopleCompleted being updated with that first person after he is completed, which
according to your advice, is not done in serviceComplete()
I suspect it's because of this code block here.
private void doServiceComplete()
{
if(sim.notBeingServed() == true)
{
System.out.println("No customer is being served at the present time"
+ " of " + sim.getTime() + ".");
}
else
{
System.out.print("Customer " + sim.getCurCust().toString() +
" finished at time " + sim.getTime() + ". Number waiting" +
" is ");
System.out.println(sim.getNumWaiting() + ".");
}
sim.serviceComplete();
}
When you get to sim.getNumWaiting() your people waiting will be one less than you're expecting. sim.serviceComplete() has peopleCompleted++ which is performed AFTER you print your results. You should move this to the beginning of the method, or somewhere else logical, before sim.getNumWaiting() is called.
Example:
private void doServiceComplete()
{
sim.serviceComplete();
if(sim.notBeingServed() == true)
{
System.out.println("No customer is being served at the present time"
+ " of " + sim.getTime() + ".");
}
else
{
System.out.print("Customer " + sim.getCurCust().toString() +
" finished at time " + sim.getTime() + ". Number waiting" +
" is ");
System.out.println(sim.getNumWaiting() + ".");
}
}