I want to find max and min values in java - java

I want max and min values of salary to display but i get same values for max and min. Here's my code:
import java.util.*;
class Wage {
String employee_name, skill;
int hours;
double sum;
String[] sno = {"1", "2", "3", "4"};
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
Scanner s = new Scanner(System.in);
public void getEmployeeDetails() {
System.out.println("Welcome to Use General Wage Record System");
for (String count : sno) {
if (count.equalsIgnoreCase("1")) {
System.out.print("Enter Name of Employee 1: ");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("2")) {
System.out.print("Enter Name of Employee 2:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee " + employee_name + "(Level " + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " " + "$" + sum);
}
}
if (count.equalsIgnoreCase("3")) {
System.out.print("Enter Name of Employee 3:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + " $" + sum);
}
}
if (count.equalsIgnoreCase("4")) {
System.out.print("Enter Name of Employee 4:");
employee_name = s.nextLine();
System.out.print("Enter the Skill Level (1,2,3) of Employee:");
Integer level_count = Integer.valueOf(s.nextLine());
if (level_count <= 3) {
System.out.print("Enter the Worked Hours for " + employee_name + ":");
hours = Integer.parseInt(s.nextLine());
if (level_count == 1) {
sum = hours * 15;
}
if (level_count == 2) {
sum = hours * 17;
}
if (level_count == 3) {
sum = hours * 21;
}
System.out.println("The wage of employee" + employee_name + "(Level" + String.valueOf(level_count) + ")" + "for" + hours + " " + "hours is" + "$ " + sum);
}
}
}
}
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
if (sum > max) {
max = sum;
System.out.println("Maximum of wage" + max + ", " + employee_name);
}
if (sum < min) {
min= sum ;
System.out.println("Minimum of Wage" + min + ", " + employee_name);
}
}
}
public class Pay {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Wage wm = new Wage();
wm.getEmployeeDetails();
wm.average();
}

In the loop of the getEmployeeDetails() method, you don't store and update the min wage, the max wage and the employee names that have these wages.
Besides, you should be more specific in the naming. For example, maxWage and minWage are more meaningful than max and min.
So, you should have maxWage, maxWageEmployeeName, minWage and minWageEmployeeName fields in the field declaration of the Wage class.
At each employee inserted in the system, you should update these values by calling a dedicated method:
public void getEmployeeDetails() {
if (count.equalsIgnoreCase("1")) {
....
updateRanking(sum, employee_name);
}
}
public void updateRanking(double actualWage, String employee_name){
if (actualWage > maxWage) {
maxWage = actualWage;
maxWageEmployeeName = employee_name;
}
else if (actualWage < minWage) {
minWage = actualWage;
minWageEmployeeName = employee_name;
}
}
Besides, your average() method called at the end of your program should only display the result and not performing comparison since you should have updated information about max, min wage and who have these as updateRanking() is called at each insertion of employee wage :
void average() {
System.out.println("\n\n");
System.out.println("stastical information for bar chart");
System.out.println("==================================");
System.out.println("Maximum of wage" + maxWage + ", " + maxWageEmployeeName );
System.out.println("Minimum of Wage" + minWage + ", " + minWageEmployeeName );
}

Related

Repeated Output, have to end the program manually

I am a beginner and not tried the following program which is giving me repeated output.. I have to end the program manually in eclipse. Not able to figure out the problem. Please advice. Any other tips are welcome.
import java.util.Scanner;
public class Sales_Amount {
public static void main(String[] args) {
final double Base_Salary = 25000;
double Commission = 0;
double Total_Salary;
double X;
double Y;
Scanner input = new Scanner(System. in );
System.out.print("Enter Sales Amount: ");
double Sales = input.nextDouble();
while (Commission < 25001) {
if (Sales <= 5000); {
Total_Salary = Base_Salary + (0.08 * Sales);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 5000 && Sales < 10001); {
X = Sales - 5000;
Total_Salary = Base_Salary + (0.08 * 5000) + (0.10 * X);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
if (Sales > 10001); {
Y = Sales - 10000;
Total_Salary = Base_Salary + (.08 * 5000) + (.10 * 10000) + (.12 * Y);
System.out.print(" Total Salary for " + Sales + "worth of Sales is: " + Total_Salary);
}
}
}
}
Add commission++ before the end of the loop.

Array Length Outcome

My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.

How do I make this if statement?

Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

program will not go to else statement

This program is supposed to print an error if you enter too many seats. If i enter an invalid number of seats ex: economy section has 8 seats. but if I enter a number greater than that it, the program doesn't go on to the else statement and print the error message.
Instead it just goes through the if statement and does the calculations with the invalid seat number.
import java.util.Scanner;
public class FlightProfit
{
String location;
int TOLEDO_FARE = 200;
int HOUSTON_FARE = 300;
int BOISE_FARE = 400;
int economySeats;
int businessSeats;
int firstClassSeats;
int economySales;
int businessSales;
int firstClassSales;
//int totalSales = economySales + businessSales + firstClassSales;
Scanner in = new Scanner(System.in);
public int addEconomySeats()
{
System.out.print("Enter number of economy seats 1-8: ");
economySeats = in.nextInt();
if(economySeats > 0 || economySeats < 9)
{
return economySeats;
}
else
{
System.out.println("Error: Only 8 seats available in economy.");
}
return 0;
}
public int addBusinessSeats()
{
System.out.print("Enter number of business seats sold: ");
businessSeats = in.nextInt();
if(businessSeats > 0 || economySeats < 7)
{
return businessSeats;
}
else
{
System.out.println("Error: Only 6 seats available in business.");
}
return 0;
}
public int addFirstClassSeats()
{
System.out.print("Enter number of first class seats sold: ");
firstClassSeats = in.nextInt();
if(firstClassSeats > 0 || firstClassSeats < 5)
{
return firstClassSeats;
}
else
{
System.out.println("Error: Only 4 seats available in first class.");
}
return 0;
}
public void getProfit(String loc)
{
location = loc;
if(location.equalsIgnoreCase("toledo"))
{
economySales = economySeats * TOLEDO_FARE;
businessSales = businessSeats * (2 * TOLEDO_FARE);
firstClassSales = firstClassSeats * (4 * TOLEDO_FARE);
System.out.println("Economy Sales: " + economySeats + " seats: " + economySales);
System.out.println("Business Sales: " + businessSeats + " seats: " + businessSales);
System.out.println("First Class Sales: " + firstClassSeats + " seats: " + firstClassSales);
//System.out.println("Total Sales: " + totalSales);
}
else if(location.equalsIgnoreCase("houston"))
{
economySales = economySeats * HOUSTON_FARE;
businessSales = businessSeats * (2 * HOUSTON_FARE);
firstClassSales = firstClassSeats * (4 * HOUSTON_FARE);
System.out.println("Economy Sales: " + economySeats + " seats: " + economySales);
System.out.println("Business Sales: " + businessSeats + " seats: " + businessSales);
System.out.println("First Class Sales: " + firstClassSeats + " seats: " + firstClassSales);
// System.out.println("Total Sales: " + totalSales);
}
else
{
economySales = economySeats * BOISE_FARE;
businessSales = businessSeats * (2 * BOISE_FARE);
firstClassSales = firstClassSeats * (4 * BOISE_FARE);
System.out.println("Economy Sales: " + economySeats + " seats: " + economySales);
System.out.println("Business Sales: " + businessSeats + " seats: " + businessSales);
System.out.println("First Class Sales: " + firstClassSeats + " seats: " + firstClassSales);
//System.out.println("Total Sales: " + totalSales);
}
}
}
==MAIN==
import java.util.Scanner;
public class Aviation
{
public Aviation()
{
}
public static void main(String[] args)
{
int option;
FlightCost newFlight = new FlightCost();
FlightProfit flight = new FlightProfit();
Scanner in = new Scanner(System.in);
System.out.print("Enter new flight location: ");
String location = in.next();
do{
String menu = "\n Please select an option to perform"
+ "\n1 (1) Get flight costs."
+ "\n2 (2) Get flight profits."
+ "\n3 (3) Enter names/meals."
+ "\n4 (4) Exit.";
System.out.println(menu);
option = in.nextInt();
}while (option < 0 || option > 4);
switch(option)
{
case 1:
newFlight.getCost(location);
break;
case 2:
flight.addEconomySeats();
flight.addBusinessSeats();
flight.addFirstClassSeats();
flight.getProfit(location);
break;
case 3:
//newFlight.flyers();
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Error: must select menu option.");
}
}
}
if (economySeats > 0 || economySeats < 9)
This condition is always true (since any number is either positive or less than 9), so of course you don't reach the else clause.
You probably want the && (and) operator :
if (economySeats > 0 && economySeats < 9)
And your other conditions have the same error.
if (economySeats > 0 && economySeats < 9)
As economySeats should be greater then 0 and smaller then 9. then only the condition will follow to the else statement.
when you use if (economySeats > 0 || economySeats < 9)
it means that economySeat should be greater then 0 (so if you input value greater then 0 then this condition will be true) so, that's why you are thinking that the if statement isnt working.
The reason why your number range check does not work as you intend to was already given. I'd howver like to hint that you could do range checks somewhat more elegant and less error-prone by using Guava's 'Range' type:
Range economySeatsRange = Range.atLeast(1).atMost(8);
//...
boolean inAllowedRange = economySeatsRange.apply(economySeats);
if(inAllowedRange)
// between 1 and 8
else
// signal error
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html

Categories

Resources