I have compiled with no errors, however I can complete the first loop no issues. However second go around it will prompt for Division name however the prompt for Number of employees does to. So I end up seeing Enter Division Name: Enter Number of Employees:
Not sure why this is happening, but I don't see anything out of place when looking.
If you see where I went wrong could you point to the line number or string of code.
Thanks.
import java.util.Scanner;
public class PayRoll {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
int employees;
double salary;
while(true) {
System.out.print("Enter Division Name: ");
name = input.nextLine();
if(name.equalsIgnoreCase("stop")) {
break;
}else {
System.out.print("Enter Number of Employees: ");
employees = input.nextInt();
while(employees <= 0) {
System.out.print("Number of Employees Must be Greater than 0, Please Re-enter: ");
employees = input.nextInt();
}
System.out.print("Enter Average Salary: ");
salary = input.nextDouble();
while(salary <= 0) {
System.out.print("Average Salary Must be Greater than 0, Please Re-enter: ");
salary = input.nextDouble();
}
Division d = new Division(name,employees,salary);
System.out.println();
System.out.println("Division " + d.getName());
System.out.println("Has " + d.getEmployees() + " Employees.");
System.out.printf("Averaging $%.2f\n",d.getSalary(),"per Employee");
System.out.printf("Making the Division total: $%.2f\n", d.getTotal());
System.out.println();
}
}
}
}
class Division {
private String name;
private int employees;
private double salary;
public Division(String name, int employees, double salary) {
this.name = name;
this.employees = employees;
this.salary = salary;
}
public double getTotal() {
return employees*salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
while(true) {
input = new Scanner(System.in);
}
Instantiate your Scanner instance input in while loop.
just add input.nextLine(); after every input.nextInt(); OR input. nextDouble(); AS:
while(true) {
System.out.print("Enter Division Name: ");
name = input.nextLine();
if(name.equalsIgnoreCase("stop")) {
break;
}else {
System.out.print("Enter Number of Employees: ");
employees = input.nextInt();
input.nextLine(); // Add it Here
while(employees <= 0) {
System.out.print("Number of Employees Must be Greater than 0, Please Re-enter: ");
employees = input.nextInt();
input.nextLine();
}
System.out.print("Enter Average Salary: ");
salary = input.nextDouble();
input.nextLine();
while(salary <= 0) {
System.out.print("Average Salary Must be Greater than 0, Please Re-enter: ");
salary = input.nextDouble();
input.nextLine();
}
// Rest of the Code
}
To understand why you need to do this , Read Java Documentation
create a counter variable out of the while loop. let's say counter == 0, increment it at the end of the loop so you won't create a problem in the initial loop using my solution.
int counter = 0;
While(){
System.out.print("Enter Division Name: ");
if(counter != 0){
input.nextLine();
}
name = input.nextLine();
counter++;
}
Related
I am trying to allow the user to submit their test scores then get the total scores and the average score. I have a separate class called student to help simplify some tasks.
This is the Student Class:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}public void addQuiz(int score){
numOfQuizzes++;
totalScore += score;
}public double getTotalScore() {
return totalScore;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then this is my main class so far.
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
This is the current output.
What is your name? tom
Please enter your scores (q to quit): 13
Please enter your scores (q to quit): 12
Please enter your scores (q to quit): 5
Please enter your scores (q to quit): q
Students Name: tom
Total Quiz Scores: 0.0
Average Quiz Score: NaN
When you read in your values, you need to check whether it's a string or an int, you only want to add integers. You might do something like:
try{
do{
String q = scoreInput.nextLine();
if(q.equals("q"){
//Do something, like break
break;
}
int numVal = Integer.valueOf(q);
scores.addQuiz(numVal);
} catch (Exception e){
//Handle error of converting string to int
}
}while(true);
//Once you have all the scores, be sure to call your averageScore method
averageScore();
Once you have the scores, your average score method should be something like:
public double averageScore(){
if(scores != null){
for(int score : scores){
totalScore += score;
}
return totalScore/scores.size();
}
Your Student class might look like this:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
}public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double averageScore(){
if(scores != null){
for(int score : scores){
totalScore += score;
}
return totalScore/scores.size();
}
}
I need to fix my addQuiz() in my student class. Then, with that class, I pull all the info into my main of prog2. I have everything working except two things. I need to get the formula fixed for my addQuiz() so it totals the amount of points entered, and fix the while statement in my main so that I can enter a word to tell the program that I am done entering my quizzes.
Here is my main file.
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Student student = new Student();
//creates array for quizzes
double[] grades = new double[99];
//counter for total number of quizzes
int num = 0;
//requests user to enter students name
System.out.print("Enter name of student: ");
String name = in .nextLine();
//requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in .nextInt();
while (quiz >= 1) {
System.out.print("Enter students quiz grades: ");
quiz = in .nextInt();
grades[num] = quiz;
num++;
}
//prints the name, total, and average of students grades
System.out.println();
System.out.println(name);
System.out.printf("\nTotal: ", student.addQuiz(grades, num));
System.out.printf("\nAverage: %1.2f", student.Average(grades, num));
}
}
here is my student file:
public class Student {
private String name;
private int total;
private int quiz;
static int num;
public Student() {
super();
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getQuiz() {
return quiz;
}
public void setQuiz(int quiz) {
this.quiz = quiz;
}
public static double addQuiz( double[] grades, int num){
int totalQuiz = 0;
for( int x = 0; x < num; x++){
totalQuiz += grades[x];
}
return totalQuiz;
}
public static double Average( double[] grades, int num){
double sum = 0;
for( int x = 0; x < num; x++){
sum += grades [x];
}
return (double) sum / num;
}
}
Any help would be much appreciated!
Your requirement is not clear but as I guess it should be something like this.
Prog2 class:
public static void main(String[] args) {
// requests user to enter students name
System.out.print("Enter name of student: ");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
Student student = new Student(name);
System.out.print("Enter number of quiz: ");
int count = in.nextInt();
for (int i = 0; i < count; i++) {
// requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in.nextInt();
student.addGrade(quiz);
}
// prints the name, total, and average of students grades
System.out.println(name);
System.out.println("Total: " + student.getTotal());
System.out.println("Average: " + student.getAverage());
}
Student class:
private String name;
private List<Double> grades = new ArrayList<Double>();
public Student(String name) {
super();
this.name= name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGrade(double grade) {
this.grades.add(grade);
}
public double getTotal() {
double total = 0;
for (double grade : grades) {
total += grade;
}
return total;
}
public double getAverage() {
return (double) getTotal() / grades.size();
}
Accept the answer if it helps.
Well for the stop condition you could try something like this
String stopFrase="stop";
String userInput="";
int quiz;
//Other code
for(;;) //This basically means loop until I stop you
{
System.out.print("Enter students quiz grades type 'stop' to finish:");
userInput=in.nextLine();
if(userInput.equals(stopFrace))
{
break;//Stop the loop
}
quiz= Integer.parseInt(userInput);
//The rest of your code
}
Your addQuiz() method seems fine, if you are not getting the desired result please check your parameters, specifically make sure that number matches the number of quiz entered.
In my program, I want to transfer credits between two person. All of the info I have added in the arrayList. Each person is given an ID.
To make transaction, user have to enter ID.
The withdraw amount enterd by the user must be subtracted from the particular account and eventually that amount must be added with another particular account, depending on the ID chosen by user. How to do that?
Basically, I don't know how to check the amount/credit with the matching ID, and then performing arithmetic task within that specific person's amount.
Actually the part I am concentrating on is switch (option2) in my code.
This is my code I am working on.
AboutPerson:
public static void main(String[] args) {
String name;
int id;
int option1;
int option2;
double credit;
int withdraw_id;
double withdraw_amount;
double dep_id;
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "3. Transfer credits\n"//need help here
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
case 3:
//transfer credit
System.out.println("To transfer credit between two persons enter 1");//working with this one
System.out.println("To transfer credit within the same persons enter 2");//not focusing on that now
option2 = input.nextInt();
input.nextLine();
switch (option2) {
case 1:
System.out.println("Enter the ID of the person you want to withdraw amount from: ");
withdraw_id = input.nextInt();
System.out.println("Enter withdraw amount: ");
withdraw_amount = input.nextDouble();
//subtract that credit from that account
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
//the amount has been withdrawn will be deposited
//add that credit
System.out.println("Done!\tTo print them out out choose option 2");
break;
}
}
}
}
PersonInfo:
package aboutperson;
public class PersonInfo {
private String name;
private int id;
private double credit;
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setCredit(double credit) {
this.credit = credit;
}
#Override
public String toString() {
return name + "\t\t" + id + "\t\t" + credit;
}
}
First add getCredit and getID methods to PersonInfo:
public double getCredit() {
return this.credit;
}
public int getID() {
return this.id;
}
And then simply exchange it between the two accounts:
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
input.nextLine();
System.out.println("Enter your ID: ");
withdraw_id = input.nextDouble();
input.nextLine();
System.out.println(": ");
withdraw_amount = input.nextDouble();
input.nextLine();
PersonInfo fromPerson = null;
PersonInfo toPerson = null;
//find PersonInfo objects from list:
for (PersonInfo pi : info) {
if (pi.getID() == dep_id) {
toPerson = pi;
break;
}
}
for (PersonInfo pi : info) {
if (pi.getID() == withdraw_id) {
fromPerson = pi;
break;
}
}
if (fromPerson == null || toPerson == null) {
System.out.println("Wrong IDs."); //maybe do something more user friendly here
break;
}
if (withdraw_amount > fromPerson.getCredit()) {
System.out.println("notify of error");
break;
}
fromPerson.setCredit(fromPerson.getCredit() - withdraw_amount);
toPerson.setCredit(toPerson.getCredit() + withdraw_amount);
System.out.println("Done!\tTo print them out out choose option 2");
Instead of storing PersonInfo in List, use Map where you can use key as id and value as PersonInfo itself. so it will be like:
Map<Integer, PersonInfo> info = new HashMap<Integer, PersonInfo>();
...
personInfo.setCredit(input.nextDouble());
perdonIdInfoMap.put(personInfo.getId(), personInfo);
Then when you have two id's get the info from map like:
personInfoFrom = perdonIdInfoMap.get(id1);
personInfoTo = perdonIdInfoMap.get(id2);
//now deduct from one and add to other like personInfoFrom.setCredit(personInfoFrom.getCridit() + personInfoTo.getCredit());
You can iterate over the list and check:
for(PersonInfo person: info){
if(person.getId().equals(searchedId)){
/* here you can do operation on that person*/
/* Printing the balance */
System.out.println("Balance: " + person.getCredit());
/* Adding or subtracting money*/
person.setCredit(person.getCredit() + ammount);
/* Other stuff*/
}
}
Or you could use a Map as SMA suggested
I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}
Ok, so I had to modify my already working program to use 2 separate classes...one to perform the task and one to store info. Once it does the first calculation and it gets to the second entry, it skips over employee name. Why? Please help. Here is the code:
package payroll_program_3;
import java.util.Scanner;
public class payroll_program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
employee_info theEmployee = new employee_info();
String eName = "";
double Hours = 0.0;
double Rate = 0.0;
while(true)
{
System.out.print("\nEnter Employee's Name: ");
eName = input.nextLine();
theEmployee.setName(eName);
if (eName.equalsIgnoreCase("stop"))
{ return;
}
System.out.print("\nEnter Employee's Hours Worked: ");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
while (Hours <0) { System.out.printf("Hours cannot be negative\n");
System.out.printf("Please enter hours worked\n");
Hours = input.nextDouble();
theEmployee.setHours(Hours);
}
System.out.print("\nEnter Employee's Rate of Pay: ");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
while (Rate <0) { System.out.printf("Pay rate cannot be negative\n");
System.out.printf("Please enter hourly rate\n");
Rate = input.nextDouble();
theEmployee.setRate(Rate);
}
System.out.print("\n Employee Name: " + theEmployee.getName());
System.out.print("\n Employee Hours Worked: " + theEmployee.getHours());
System.out.print("\n Employee Rate of Pay: " + theEmployee.getRate() + "\n\n");
System.out.printf("\n %s's Gross Pay: $%.2f\n\n\n", theEmployee.getName(), theEmployee.calculatePay());
}
}
}
PART 2:
package payroll_program_3;
public class employee_info
{
String employeeName;
double employeeRate;
double employeeHours;
public employee_info()
{
employeeName = "";
employeeRate = 0;
employeeHours = 0;
}
public void setName(String name)
{
employeeName = name;
}
public void setRate(double rate)
{
employeeRate = rate;
}
public void setHours(double hours)
{
employeeHours = hours;
}
public String getName()
{
return employeeName;
}
public double getRate()
{
return employeeRate;
}
public double getHours()
{
return employeeHours;
}
public double calculatePay()
{
return (employeeRate * employeeHours);
}
}
There are two places where an infinite loop can occurring, as Hours & Rate are not changing inside of them.
while (Hours <0)
{
System.out.printf("Hours cannot be negative\n");
System.out.printf("Please enter hours worked\n");
}
while (Rate <0)
{
System.out.printf("Pay rate cannot be negative\n");
System.out.printf("Please enter hourly rate\n");
}
Haven't read all the code, but it is likely this needs to be an if statement containing a continue.
You need hours= input.next double to change hour var so it fails the while condition