public static void main(String[] args) {
//Scanner declaration and other stuff
//...
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price2 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating2 = scan.nextInt();
scan.nextLine();
}
public static void compare(camera camOne, camera camTwo) {
int value1 = camOne.computeValue();
int value2 = camTwo.computeValue();
/*
* if(camOne.computeValue() == camTwo.computeValue() && userRating1 ==
* userRating2)
*/
}
How would I be able to call the price or the userRating inputs into the compare method, where I would like to compare the values?
You wouldn't use Scanner inside of the compare method. You're comparing two camera objects (which should be renamed Camera), and the Camera objects that you wish to compare should be fully formed before entering the method, and so there should be no need to use a Scanner inside the method.
public static void main(String[] args) {
//Scanner declaration and other stuff
//...
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating1 = scan.nextInt();
scan.nextLine();
System.out.println("Enter price in $ (0.00 to 1000.00)");
int price2 = scan.nextInt();
scan.nextLine();
System.out.println("Enter user rating (0 to 5)");
int userRating2 = scan.nextInt();
scan.nextLine();
// not sure what constructor Camera has
Camera camera1 = new Camera(....);
Camera camera2 = new Camera(....);
int result = compare(camera1, camera2);
System.out.println("Result is: " + result);
}
// shouldn't this return an int? also camera should be renamed Camera
public static int compare(Camera camOne, Camera camTwo) {
int value1 = camOne.computeValue();
int value2 = camTwo.computeValue();
/*
* if(camOne.computeValue() == camTwo.computeValue() && userRating1 ==
* userRating2)
*/
int result = Integer.compare(value1, value2);
return result; // 0 for the same, 1 for first one > second, -1 for opposite
}
Also, you ask:
How would I be able to call the price or the userRating inputs into the compare method, where I would like to compare the values?
Assuming that your Camera class (again, rename it from "camera" to "Camera" to comply with Java naming conventions) has both a getPrice() and a getUserRating() method, then you'd call those methods on your camOne and camTwo Camera parameters inside of the compare(...) method. If you need to compare doubles, I suggest that you use the Double.compare(double d1, double d2) method, and if you need to compare ints, then use the Integer.compare(int i1, int i2) method.
For example, using a Comparator,
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TestCamera {
public static void main(String[] args) {
ArrayList<MyCamera> cameraList = new ArrayList<>();
// We'll pretent to use Scanner here to get values
cameraList.add(new MyCamera("Sony", 8, 250.00));
cameraList.add(new MyCamera("Olympus", 7, 450.0));
cameraList.add(new MyCamera("Nikon", 10, 400.0));
cameraList.add(new MyCamera("Fuji", 7, 450.50));
System.out.println("Pre-sorted list:");
for (MyCamera myCamera : cameraList) {
System.out.println(myCamera);
}
System.out.println();
System.out.println("Post-sorted list:");
Collections.sort(cameraList, new MyCameraComparator(false));
for (MyCamera myCamera : cameraList) {
System.out.println(myCamera);
}
}
}
class MyCamera {
private int rating;
private double cost;
private String name;
public MyCamera(String name, int rating, double cost) {
this.name = name;
this.rating = rating;
this.cost = cost;
}
public String getName() {
return name;
}
public int getRating() {
return rating;
}
public double getCost() {
return cost;
}
#Override
public String toString() {
return "MyCamera [rating=" + rating + ", cost=" + cost + ", name=" + name
+ "]";
}
}
class MyCameraComparator implements Comparator<MyCamera> {
private boolean lowestToHighest = true;
public MyCameraComparator() {
// default constructor
}
public MyCameraComparator(boolean lowestToHighest) {
this.lowestToHighest = lowestToHighest;
}
#Override
public int compare(MyCamera cam1, MyCamera cam2) {
int finalResult = 0;
int ratingValue = Integer.compare(cam1.getRating(), cam2.getRating());
if (ratingValue != 0) {
finalResult = ratingValue;
} else {
finalResult = Double.compare(cam1.getCost(), cam2.getCost());
}
if (lowestToHighest) {
return finalResult;
} else {
return -finalResult;
}
}
}
Related
I am trying to create a class that receives data about a person's name, exam subject, and exam score. I have these classes so far:
APExam:
public class APExam {
//instance variables
private String mySubject;
private int myScore;
//constructors
public APExam(String subject, int score) {
mySubject = subject;
myScore = score;
}
public APExam() {
mySubject = "";
myScore = 1;
}
//getters and setters
public void setSubject(String s) {
mySubject = s;
}
public String getSubject() {
return mySubject;
}
public void setScore(int score) {
myScore = score;
}
public int getScore() {
return myScore;
}
//compareTo
public String compareTo(int s) {
if(myScore == s)
return "Scores are equal.";
else if(myScore > s)
return "The first score is greater than the second score.";
else
return "The second score is greater than the first score.";
}
//equals
public boolean equals(String str) {
return mySubject.equals(str);
}
//toString
public String toString() {
return "Subject: " + mySubject + "\nScore: " + myScore;
}
}
APStudent:
public class APStudent {
//instance variables
private String myFirstName;
private String myLastName;
private ArrayList<APExam> myExams = new ArrayList<APExam>();
//constructors
public APStudent(String fname, String lname) {
myFirstName = fname;
myLastName = lname;
}
public APStudent() {
myFirstName = "";
myLastName = "";
}
//getters and setters
public void setFirstName(String fname) {
myFirstName = fname;
}
public String getFirstName() {
return myFirstName;
}
public void setLastName(String lname) {
myLastName = lname;
}
public String getLastName() {
return myLastName;
}
public ArrayList<APExam> getExams() {
return myExams;
}
//addExam
public void addExam(APExam ex) {
myExams.add(ex);
}
//computeExamAverage
public double computeExamAverage(List<APExam> exams) {
int sum = 0;
for(int i = 0; i < exams.size(); i++) {
sum += exams.get(i).getScore();
}
return (double) sum / exams.size();
}
//findHighestExamScore
public int findHighestExamScore(List<APExam> exams) {
int max = exams.get(0).getScore();
for(APExam ex : exams) {
if(ex.getScore() > max) {
max = ex.getScore();
}
}
return max;
}
//numberOfFives
public int numberOfFives(List<APExam> exams) {
int fiveCount = 0;
for(APExam ex : exams) {
if(ex.getScore() == 5) {
fiveCount++;
}
}
return fiveCount;
}
}
ArrayListTest:
public class ArrayListTest {
public static void main(String[] args) {
//instance variables
final String QUIT = "end";
Scanner sc = new Scanner(System.in);
ArrayList<APExam> myExams = new ArrayList<APExam>();
APStudent student = new APStudent();
String fname, lname, sub, input = "";
int score;
//prompt for info
System.out.print("Enter first name: ");
fname = sc.nextLine();
student.setFirstName(fname);
System.out.print("\nEnter last name: ");
lname = sc.nextLine();
student.setLastName(lname);
while(!input.equals(QUIT)) {
APExam ap = new APExam();
System.out.print("\nEnter exam subject or 'end' to quit: ");
input = sc.nextLine();
sub = input;
ap.setSubject(sub);
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
ap.setScore(score);
student.addExam(ap);
sc.nextLine();
}
//display information
System.out.println(student.getExams());
System.out.println("Name: " + student.getFirstName() + " " + student.getLastName());
System.out.println("Exam average score: " + student.computeExamAverage(myExams));
System.out.println("Highest score: " + student.findHighestExamScore(myExams));
System.out.println("Number of fives: " + student.numberOfFives(myExams));
System.out.println();
for(int i = 0; i < myExams.size(); i++) {
System.out.println(myExams.get(i));
}
//prompt for search
System.out.println("1 sequential search"
+ "\n2 binary search"
+ "\n3 exit");
input = sc.nextLine();
while(!((input.equals("1") || input.equals("2") || input.equals("3")))) {
switch(input) {
case "1":
sequentialSearch(myExams, 3);
break;
case "2":
binarySearch(myExams, 2);
break;
case "3":
break;
}
}
}
}
For some reason in the ArrayListTest class it doesn't create an APExam object with the inputted scores and subjects. Is there something wrong with the while loop? Or is something else wrong?
Your problem is that you are for some reason passing variable List<APExam> exams into your functions. When you are doing that you are passing a empty ArrayList<APExam> and that's why it throws a IndexOutOfBoundsException.
You shouldn't pass anything and just use the APStudent's myExams list.
public double computeExamAverage() {
double sum = 0;
for (APExam myExam : myExams) {
sum += myExam.getScore();
}
return sum / myExams.size();
}
public int findHighestExamScore() {
int max = 0;
for(APExam exam : myExams) {
if(exam.getScore() > max) max = exam.getScore();
}
return max;
}
public int numberOfFives() {
return (int) myExams.stream().filter(apExam -> apExam.getScore() == 5).count();
}
EDIT: I would like to comment on your main method too. You should use the parametrized constructors instead of default one and setters. And you should check on the input being "end" before you ask for grade.
public static void main(String[] args) {
final String QUIT = "end"; // not really necessary, but ok
Scanner sc = new Scanner(System.in);
String firstName, lastName, subject;
int score;
//prompt for info
System.out.print("Enter first name: ");
firstName = sc.nextLine();
System.out.print("\nEnter last name: ");
lastName = sc.nextLine();
APStudent student = new APStudent(firstName, lastName); // use of parametrized constructor
while(true) {
System.out.print("\nEnter exam subject or 'end' to quit: ");
subject = sc.nextLine();
if (subject.equals(QUIT)) break; // check if user wants to end it
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
student.addExam(new APExam(subject, score)); // use of parametrized constructor
sc.nextLine();
}
sc.close(); // never forget to close Scanner
//display information etc.
}
I'm a beginner in java. I have a problem with my code. I want to design my program but I stuck in ArrayList. How can I add a new price and display all food has price smaller or equals than the price of a new food? and sort the list f by price. Help me please, thank so much.
1.accept a new price named p: list all Food which have price <= p
2.sort list f ascending by price and output list after sorting
public class Food {
//states
private String name;
private double price;
//accessor
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
//mutator
public String getName() {
return name;
}
public double getPrice() {
return price;
}
//methods
public Food() {
name = "";
price = 0;
}
public Food(String name, double price) {
this.name = name;
this.price = price;
}
public double getSalePrice() {
double tax = 0.07;//7%;
if(name.toLowerCase().startsWith("k")) tax = 0.05;
return price + price * tax;
}
public void print() {
System.out.printf("%-20s%-10.1f ($)%-10.1f ($)\n",
name,price,getSalePrice());
//System.out.println(String.format("%-20s%-10.1f ($)%-10.1f ($)\n",
// name,price,getSalePrice()));
}
public int listp(ArrayList<Food> f, int priceP) {
int s,i,n;
n = f.size();
s = 0;
for(i=0;i<n;i++) {
if(f.get(i).price > priceP) s++;
}
return(s);
}
}
public class Main {
public static void main(String[] args) {
//a list of food
Scanner in = new Scanner(System.in);
final int MAX = 10;
Food [] f = new Food[MAX];
f[0] = new Food("BBQ",3.35);
f[1] = new Food("KFC",3.3);
f[2] = new Food("Ga 36",4.5);
int n = 3;
while(true) {
System.out.print("Enter food name: ");
String name = in.nextLine();
System.out.print("Enter food price: ");
double price = Double.parseDouble(in.nextLine());
f[n] = new Food();
//f[n].name = name;f[n].price = price;
f[n].setName(name);
f[n].setPrice(price);
n++;
System.out.print("Add more food (yes/no)? ");
String s = in.nextLine();
if(s.equalsIgnoreCase("no")) break;
}
//output list
for (int i = 0; i < n; i++) {
f[i].print();
}
System.out.print("Enter price of food p:");
double price = Double.parseDouble(in.nextLine());
System.out.println(listp(f,price));
}
public int listp(ArrayList<Food> f, int priceP) {
int s,i,n;
n = f.size();
s = 0;
for(i=0;i<n;i++) {
if(f.get(i).getPrice() > priceP) s++;
}
return(s);
}
}
Here is a working solution where the array was converted to a list and the listp method was changed to use streams which are really a good fit for your requirements:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//a list of food
Scanner in = new Scanner(System.in);
List<Food> f = new ArrayList<>();
f.add(new Food("BBQ", 3.35));
f.add(new Food("KFC", 3.3));
f.add(new Food("Ga 36", 4.5));
int n = 3;
while (true) {
System.out.print("Enter food name: ");
String name = in.nextLine();
System.out.print("Enter food price: ");
double price = Double.parseDouble(in.nextLine());
Food food = new Food();
//f[n].name = name;f[n].price = price;
food.setName(name);
food.setPrice(price);
f.add(food);
n++;
System.out.print("Add more food (yes/no)? ");
String s = in.nextLine();
System.out.println(s);
if (s.trim().equalsIgnoreCase("no")) break;
}
System.out.print("Enter price of food p:");
double price = Double.parseDouble(in.nextLine());
listp(f, price);
}
private static void listp(List<Food> f, double priceP) {
f.stream()
.filter(food -> food.getPrice() <= priceP)
.sorted(Comparator.comparingDouble(Food::getPrice))
.forEach(food -> System.out.printf("%s : %s%n", food.getName(), food.getPrice()));
}
}
Here is a variation of the listp method which allows you to limit the list by a number:
private static void listp(List<Food> f, double priceP, int limit) {
f.stream()
.filter(food -> food.getPrice() <= priceP)
.sorted(Comparator.comparingDouble(Food::getPrice))
.limit(limit)
.forEach(food -> System.out.printf("%s : %s%n", food.getName(), food.getPrice()));
}
This ensures that the printed out list is always as long as specified in the limit parameter.
Usage example:
listp(f, price, 2);
This will print a maximum of two items, even if the total list has more than that.
1.
public List<Food> findFoodWhichPriceLessThan(Collection<Food> listOfFood, double price){
return listOfFood.stream().filter(it -> it.getPrice() <= price).collect(Collectors.toList());
}
2.
public void sortFoodByPrice(List<Food> listOfFood){
Collections.sort(listOfFood, Comparator.comparingDouble(Food::getPrice));
}
or
public List<Food> sortFoodByPrice2(List<Food> listOfFood){
return listOfFood.stream().sorted(Comparator.comparingDouble(Food::getPrice)).collect(Collectors.toList());
}
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
In this program I wrote I have to print out the name of the customer who spent the most in the store. I need help searching the array list for the customer who spent the most.
package bestcustomer;
import java.util.*;
/**
*
* #author muf15
*/
public class BestCustomer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
sales.add(salesAmount);
System.out.println("Enter customers name");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales;
return name;
}
}
You should wrap these two field in a class called probably Customer and then
Use Collections.max();
Collections.max(yourCollection, customComparator);
You should consider making Customer a class, but this would find the name with your current data structures:
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales = 0;
int index = -1;
for(int i = 0; i < sales.size(); i++) {
if(sales.get(i) > maxSales) {
index = i;
maxSales = sales.get(i);
}
}
if(index == -1) {
return null; //lists are empty
}
return customers.get(index);
}
I might be a bit late..
I think that if you create a Customer class with two fields, name and sale it would be better design as mentioned by other answers.
Then in BestCustomer you could loop through the list of customer, find the highest sales and return the name.
Something like this for BestCustomer
private ArrayList<Customer> customers = new ArrayList<Customer>();
public BestCustomer(){
Scanner in = new Scanner(System.in);
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
System.out.println("Enter customers name");
String name = in.next();
customers.add(new Customer(name, salesAmount));
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer();
System.out.print(bestCustomer);
}
private double highestSale(){
double highestSale = 0;
for(Customer c: customers)
if (c.getSales() > highestSale)
highestSale = c.getSales();
return highestSale;
}
public String nameOfBestCustomer(){
for (Customer c: customers)
if(c.matchSale(highestSale()))
return c.getName();
return null;
}
}
and this is the Customer
public class Customer {
private String name;
private double sales;
public Customer(String name, double salesAmount) {
this.name = name;
sales = salesAmount;
}
public boolean matchSale(double sales){
return this.sales == sales;
}
public double getSales(){
return sales;
}
public String getName(){
return name;
}
}
I am a beginner so I am pretty sure there is a more efficient way to do it. Also I am using two getters and as far as my understanding goes it is not the better design..
In Java8, if defined Customer like mikey said
customers.stream()
.max(Comparator.comparing(Customer::getSales))
.get()
.getName()
I am completed the whole program, and it is working fine. But, I am having trouble with the StringTokenizer. I have class named Worker.java and a test class named TestWorker.java...
In the test class I have calculated and printed out the total hoursworked, grossSalary and etc..
But I am stuck in 1 position, that is I have to store name,id, and hourly rate in array, and then using the StringTokenizer, I have to prompt the user to enter worker ID and hourly rate.
When the user enter the user worker name and ID, the program output will show the user the hourly rate of the worker...
or in other words...
Allow the user to enter worker-ID and Hours repeatedly until user enter and empty string. Read the values and invoke the methods addWeekly() on the appropriate object(by searching through the array to locate the object with the specified ID). If a nonexistent ID is entered display an appropriate error message.
Please see my codings below and modify as your needs....
//Worker.java
public class Worker {
public final double bonus=100;
protected String name;
protected String workerID;
protected double hourlyRate;
protected double hoursWorked;
protected double weekHour;
protected double tax;
protected double grossSalary;
protected double netSalary;
public Worker() {
}
public Worker(String name,String workerID,double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double weekHour){
hoursWorked = hoursWorked + weekHour;
}
public double gross()
{
grossSalary = (hoursWorked*hourlyRate);
if(hoursWorked>=150)
{
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double taxAndNet()
{
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary-tax);
return netSalary;
}
public String getName()
{
return name;
}
public String getWorkerID()
{
return workerID;
}
public double getHourly()
{
return hourlyRate;
}
public double getTotalHours()
{
return hoursWorked;
}
public double getGrossSalary()
{
return grossSalary;
}
public void addToGross(double amt)
{
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name :" + name + "\nID :" + workerID +"\nHourly rate : "+ hourlyRate +"\nTotal Hours Worked " + hoursWorked +"\nGross Pay: "+getGrossSalary()+ "\nTax : "+tax +"\nNetpay :" +netSalary);
}
}
//TestWorker.java
import java.util.StringTokenizer;
import java.util.Scanner;
public class TestWorker {
public static void main(String args[]) {
Worker e = new Worker("John Major","s123",15.0);
e.addWeekly(45);
e.addWeekly(40);
e.addWeekly(32);
e.addWeekly(38);
e.gross();
e.taxAndNet();
e.displaySalary();
Worker[] worklist = new Worker[5];
worklist[0] = new Worker("Richard Cooper","s1235",20.0);
worklist[1] = new Worker("John Major","s1236",18.0);
worklist[2] = new Worker("Mary Thatcher","s1237",15.0);
worklist[3] = new Worker("David Benjamin","s1238",16.0);
worklist[4] = new Worker("Jack Soo","s1239",25.0);
Scanner input = new Scanner(System.in);
String name;
do{
System.out.print("Please enter your name and worker ID: ");
name = input.nextLine();
StringTokenizer string = new StringTokenizer(name,"+");
System.out.println("******|||||*******");
while(string.hasMoreElements()){
System.out.println(string.nextElement());
}
}
while(name.isEmpty()==false);
String s = "Five+Three=Nine-One";
String arr[];
//declare it with 3 tokens as seen above:
StringTokenizer st = new StringTokenizer(s, "+=-");
//the array size is the number of tokens in the String:
arr = new String[st.countTokens()];
//when there are still more tokens, place it in the array:
int i = 0;
while(st.hasMoreTokens()){
arr[i] = st.nextToken();
i++;
}
//determine the word with the largest length:
int indexMax = 0;
for( i = 1; i < arr.length; i++){
if(arr[i].length() > arr[indexMax].length())
indexMax = i;
}
System.out.println("The largest element is in index: "
+ indexMax);
} //main
} //class
Please tell us your java version. Since jdk 1.4.2 you should use String.split(...) instead of the old Stringtokenizer. Check out this tutorial TIP: A little tutorial about String.split();