java programming with this class - java

Hey I'm writing a java class and the result has to be from this image
.
The whole program works great but in the end i don't get the correct math output. I think it some problem in my equation. Can someone help me with the problem. Thank you
import java.util.Scanner;
import java.awt.Toolkit;
public class Sports
{
public static void main(String[] args)
{
//create scanner object
Scanner input=new Scanner(System.in);
//create tolkit object
Toolkit tk=Toolkit.getDefaultToolkit();
int players;
int team=15;
System.out.println("SporT's Team Calculator");
System.out.println("=======================");
System.out.println("Enter the Total number of players===>");
players=input.nextInt();
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
players=input.nextInt();
while(players>15 || players<9 )
{
tk.beep();
System.out.println("\nInvalid number of players per team, please re-enter...");
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
players=input.nextInt();
players=players%team;
}
System.out.println("There will be " + players + " teams, "
+ "with " + players + " players " + "left over.");
System.out.println("\nThank you for using SporT's Software!");
}
}

You are saving both the total number of players and the number of players on a team into the same variable players. If you were to answer that the total number of players is 142 it'll immediately be overwritten by the next assignment to players for the number per team. These should be separate variables int playersPerTeam for instance

First, you are working with java so the variable
players
will constantly gets overridden.
To solve this, divide the variable
players
into 2 different variables, one to count the number of players(total) and another to count the number of players per team. This also means that you will need to change the part when you continuously ask the user for a valid input set (in the while loop) .
Secondly, your math in calculating your total number of teams and the players left over are incorrect. Below, I included a working version:
int numTeams = totalPlayers / playersPerTeam;
int playersLeft = totalPlayers - (playersPerTeam * numTeams);
System.out.println("There will be " + numTeams + " teams, " + "with " + playersLeft + " players " + "left over.");

It seems like you are retrieving two pieces of information: the total number of players and the players per team. So you will need two variables to store both pieces of information. Instead of overriding the same variable - losing the first piece of information collected.
The Equations:
To get the number of teams:
(int)(players / playerPerTeam)
To get the number of left over players:
players-playerPerTeam*totalTeams
Also I don't understand why you are getting two different numbers, 11 and 10, for the same variable, players in the console.

i actually already figured it out but thanks.
import java.util.Scanner;
import java.awt.Toolkit;
public class Sports
{
public static void main(String[] args)
{
//create scanner object
Scanner input=new Scanner(System.in);
//create tolkit object
Toolkit tk=Toolkit.getDefaultToolkit();
int players;
int team;
System.out.println("SporT's Team Calculator");
System.out.println("=======================");
System.out.println("Enter the Total number of players===>");
players=input.nextInt();
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
team=input.nextInt();
while(team>15 || team<9 )
{
tk.beep();
System.out.println("\nInvalid number of players per team, please re-enter...");
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
team=input.nextInt();
}
int result=players/team;
int player= players%team;
System.out.println("There will be " + result + " teams, "
+ "with " + player + " players" + " left over.");
System.out.println("\nThank you for using SporT's Software!");
}
}

Related

How can I fix this java?

I am working on this program with these instructions:
Bus Passengers: Write a program that is to be used to count how many passengers are travelling on
buses that pass a particular bus stop in a given hour. It should use a while loop to repeatedly ask the user to give the number of passengers on the bus that just passed. It should stop when the special code X is entered as the number of passengers. It should then give the number of buses and the total number of passengers counted in that hour. For example, one run might be as follows.
How many passengers were on the bus? 2
How many passengers were on the bus? 5
How many passengers were on the bus? 10
How many passengers were on the bus? 3
How many passengers were on the bus? 12
How many passengers were on the bus? 1
How many passengers were on the bus? 0
How many passengers were on the bus? X
There were a total of 33 passengers on 7 buses.
I am trying to fix an error:
Few points to note:-
You don't need System.exit()
In java variables are only accessible inside their scope i.e. the region they are created in.
I tried to rewrite code as following:-
import java.util.Scanner;
public class Bus {
int busCount =0;
int passengerCount =0;
Scanner scanner= new Scanner(System.in);
public static void main(String args[]){
Bus bus = new Bus();
bus.getResults();
}
private void addBusAndPassenger(String input){
try{
int a = Integer.parseInt(input);
busCount = busCount + 1;
passengerCount = passengerCount + a;
}catch(NumberFormatException e){
System.out.println("Please provide integer or X as input");
}
}
private void getResults(){
String a =null;
while (!("X".equals(a))){
System.out.print("How many passengers were on the bus? ");
a = scanner.nextLine();
if("X".equals(a))
break;
addBusAndPassenger(a);
}
System.out.println("There were a total of " + passengerCount + " passengers on " + busCount + " buses.");
}
}
A few things here. Other people pointed this out, but you need to pass parameters to your method. The method signature is there for a reason - your method calls must match the method signature you define.
Also, busInformation is supposed to return an int, but it returns nothing.
Also, this line:
Integer.parseInt(a);
does nothing - you throw away the result immediately. It won't modify the string in place or anything like that. (Well, I suppose that it'll throw an exception if they enter something other than an integer, but that doesn't seem to be what you're trying to do with this line).
At an absolute minimum, you should change the return type of your method to int and the change this line to return Integer.parseInt(a);.
(You also shouldn't be creating a new scanner every time like this - you should just re-use the same one).

How to make a counter persist in Java?

I'm making a dice game that scores points based on rolling a 7 or 11(pair of dice). The game keep track of the bets and score. The current score should be added to 3 times the bet amount if the the condition is met. However the score only changes the in the first instance the condition is met, then remain the same through any other roll attempts. I tried to set my getters and setters to be static but that didn't work. What can I do to make my counter work properly?
Program:
public Game() {
final Dice throwDice = new Dice();
//Roll Dice
rollDice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
throwDice.PairOfDice();
diceResult.setText("You rolled: " + throwDice.getDie1() +
" + " + throwDice.getDie2() +
" = " + throwDice.getTotal());
currentScore.setText("Score: $" + throwDice.getScore());
if(throwDice.getTotal() == 7 || throwDice.getTotal() == 11) {
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
currentScore.setText("Score: $" + throwDice.getScore());
}
}
});
The declaration of your Dice:
Dice throwDice = new Dice();
is in actionPerformed() which means it is created every time you call that function.
Move the declaration into Game, ie. make it an attribute of a game and you should be fine.
You can safely make Dice::score, Dice::getScore() and Dice:setScore(int) non-static.
UPDATE: Given there is still an issue, perhaps try replacing:
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
with:
throwDice.setScore(throwDice.getScore() + (3 + throwDice.getBet()));
In your question you say:
The current score should be added to 3 times the bet amount
You are not adding to the current score. You are only setting the score to the 3 times the bet amount every time. So the value will not change (unless, of course, you change the bet amount).
throwDice.setScore(Integer.parseInt(input.getText()) * 3)
Instead you need to add it to the current score:
throwDice.setScore(throwDice.getScore() + Integer.parseInt(input.getText()) * 3)
You need to move
Dice throwdice = new Dice`
up the code so that it is not called every time it enters actionperformed

can i compare using .equal() for two or more things in the same time

I should Define four boolean variables as follows:
Freshman for students in levels 1 or 2.
Sophomore for students in levels between 3 and 5.
Junior for students in levels between 6 and 8.
Senior for students in levels 9 or 10.
the user enters the course code, then I decide which level is the student (user) and then define the 4 boolean variables depending on the level.
But I don't know how to do the equal() for two thing or more.
this is my code:
import java.util.*;
public class point8 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// declaring
String CourseCode, Level;
boolean Freshman, Sophomore, Junior, Senior;
// input
System.out.println("Course code:");
CourseCode = input.next().toUpperCase();
System.out.println("\nCourse Code: " + CourseCode);
// output
Level = CourseCode.substring(CourseCode.length() - 1);
System.out.println("Student Level: " + Level);
Freshman = Level.equals("1");
System.out.println("Freshman: " + Freshman);
Sophomore = Level.equals("3");
System.out.println("Sophomore: " + Sophomore);
Junior = Level.equals("6");
System.out.println("Junior: " + Junior);
Senior = Level.equals("9");
System.out.println("Senior: " + Senior);
}
}
What shall I do to compare from level 1 or 2 for freshman
and compare from level 3 to 5 for Sophomore ?
It seems to me that you're better of using integers, just parse the String to int.
For example:
int myLevel = Integer.parseInt(Level);
if(myLevel >= 3 && myLevel <= 5)
{
System.out.println("Sophomore: " + Sophomore);
}
You might get an error if the user inserts a letter instead of a number, to avoid this you need to catch the exception and handle it. This however is an entire different story, but you should readup about it: https://docs.oracle.com/javase/tutorial/essential/exceptions/
if(Level.equals("9") || Level.equals("10"))
{
//Senior
}
Update: The OR operator is something you should learn in the first couple weeks. The only thing more basic is to just write out the second if statement.
if(Level.equals("9"))
{
//Senior
}
else if(Level.equals("10"))
{
//Senior
}

Trying to compare rep sales in an array list in Java

Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}

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