Arrays JOptionPane version - java

can anyone help me with this.
the assignment is to use JOptionPane in arrays. the user will input the length of the array. then at the end of the program, it will display the largest number.
here is what i got so far:
import javax.swing.JOptionPane;
public class array
{
public static void main(String[] args)
{
String L;
int lenght;
L=JOptionPane.showInputDialog(null,"enter lenght: ");
lenght=Integer.parseInt(L);
int[]num = new int[lenght];
for(int counter = 0; counter < lenght ;counter++)
{
JOptionPane.showInputDialog(null,"enter #: "+(counter+0));
int max=num[0];
if (num[counter] > max)
{
max = num[counter];
}
}
JOptionPane.showMessageDialog(null,"the largest number is: " + max);
}
}
then there is this error:
error: cannot find symbol

maxis defined in scope of for loop. So it is not available outside of for.
Define it outside of the for loop and it should work:
public static void main(String[] args) {
String L;
int lenght;
L = JOptionPane.showInputDialog(null, "enter lenght: ");
lenght = Integer.parseInt(L);
int[] num = new int[lenght];
int max=0;
for (int counter = 0; counter < lenght; counter++) {
JOptionPane.showInputDialog(null, "enter #: " + (counter + 0));
max = num[0];
if (num[counter] > max) {
max = num[counter];
}
}
JOptionPane.showMessageDialog(null, "the largest number is: " + max);
}
Update:
You never store the input value to num[counter]
num[counter] = Integer.parseInt(JOptionPane.showInputDialog(null, "enter #: " + (counter + 0)));

package retedunits;
import java.util.Scanner;
public class RentedUnits {
private Integer TOTAL_NUMBER_RENT_UNITS; //Total number of rented units
private Double rentPerUnit; //Rent Per Unit
private Double maintainancePerUnit; //Average Maintainance cost per unit
private Integer currentUnitsRented; //Number of units currently occupied
private Double rentIncreaseFactor; //The level at which people leave
//PROFIT MAX
private Double maxRentForProfit;
private Integer maxUnitsForProfit;
public RentedUnits(Integer totalUnits, Double initalRentPerUnit, Double initialMaintainanceCost, Integer currentRented, Double rentIncreaseFactor){
this.TOTAL_NUMBER_RENT_UNITS = totalUnits;
this.rentPerUnit = initalRentPerUnit;
this.maintainancePerUnit = initialMaintainanceCost;
this.currentUnitsRented = currentRented;
this.rentIncreaseFactor = rentIncreaseFactor;
}
public Double getMaxRentForProfit() {
return maxRentForProfit;
}
public Integer getMaxUnitsForProfit() {
return maxUnitsForProfit;
}
private void increaseRent(Double increasedRent){
//For each $40 increase in rent one unit is vacant.
if(increasedRent > this.rentIncreaseFactor) {
//The number of units that will become vacant is one for every increase of rentIncreaseFactor
int numberVacate = (int) (increasedRent % this.rentIncreaseFactor);
this.currentUnitsRented -= numberVacate;
this.rentPerUnit += increasedRent;
}
else {
this.rentPerUnit += increasedRent;
}
}
private Double calculateProfit(){
//Calculate total rent collected from units that are rented
Double totalRent = this.currentUnitsRented * this.rentPerUnit;
//calculate the maintainanec of all units
Double totalMaintainence = this.TOTAL_NUMBER_RENT_UNITS * this.maintainancePerUnit;
return totalRent - totalMaintainence;
}
public void maximizeProfit(){
/*Keep increasing rent, and let people leave till the total collected
* rent keeps increasing.
*/
/* Assume you begin at all units occupied*/
Double maximumProfit = 0.0;
Double maxProfitRent = 0.0;
Integer maxProfitUnits = 0;
/* Keep increasing rent till all people leave while tracking max profit*/
while(this.currentUnitsRented == 0){
increaseRent(this.rentIncreaseFactor);
if(this.calculateProfit() > maximumProfit){
maximumProfit = this.calculateProfit();
maxProfitRent = this.rentPerUnit;
maxProfitUnits = this.currentUnitsRented;
}
}
this.maxRentForProfit= maxProfitRent;
this.maxUnitsForProfit = maxProfitUnits;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
RentedUnits rentedUnits = new RentedUnits(50, 600.0, 27.0, 50, 40.0);
rentedUnits.maximizeProfit();
System.out.println(rentedUnits.getMaxUnitsForProfit() + " units needs to be rented at " + rentedUnits.getMaxRentForProfit() + " rent per unit to get maximum profit.");
}
}

Related

Java Average of integers

i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.
Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);

What am I missing from my code to meet all the requirements of my program?

I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.
public class Table {
public static void main(String [] strAng) {
int sum = 0;
double average;
int min = 1;
int max = 10;
for(int number = min;
number <= max; ++number) {
sum += number;
}
System.out.print("Sum:" +sum);
System.out.print("Average:" +average);
You have not get an input from user and also you do nothing to make average.
Try this code, and if you have other requirements, update the question.
int sum = 0;
double average;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the integers with space between each two integer: ");
String inputNumberFilePath = userInputScanner.nextLine();
String[] numStrArray = inputNumberFilePath.split(" ");
for (String string : numStrArray) {
sum += Integer.parseInt(string);
}
average = (double) sum / (double) numStrArray.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
output sample:
Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.
import java.util.*;
public class Table {
This part is used to read ANY user input Strings included.
public static String getInput(){
String outPut = "";
System.out.println("Type something to parse: ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextLine()) {
outPut = sc.nextLine();
}
return outPut;
}
Here we build our "bar graph":
public static Map<Long,Integer> makeTable(String input){
Map<Long,Integer> table = new HashMap<>();
long in = Long.parseLong(input);
long lastDig = 0;
int count = 1;
while(in > 0){
lastDig = in % 10;
in /= 10;
if(!table.containsKey(lastDig)) {
table.put(lastDig, count);
} else {
table.replace(lastDig,count,count+1);
}
}
return table;
}
Here we calculate the sum:
public static int sum(Map<Long,Integer> table){
int sum = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
}
return sum;
}
Here we get our average:
public static int average(Map<Long,Integer> table){
int sum = 0;
int divisor = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
divisor += table.get(key);
}
return sum/divisor;
}
public static void main(String[] args){
int sum = 0;
double average = 0;
String input = "";
input = getInput();
System.out.println("Unsanitized In: " + input);
Here the integer digits are extracted!
input = input.replaceAll("[^\\d.]","");
Long.parseLong(input);
System.out.println("Sanitized In: " + input);
Map<Long,Integer> myMap = makeTable(input);
System.out.println(myMap);
System.out.println("Sum:" +sum(myMap));
System.out.print("Average:" + average(myMap));
}
}
Our example output for: asdf45313ha is:
Unsanitized In: asdf45313ha
Sanitized In: 45313
{1=1, 3=2, 4=1, 5=1}
Sum:16
Average:3

Simulating a gas station

So I'm supposed to create a program where I have a gas station with 5 gas pumps and and I don't know how to keep track of the statistics, the program correctly subtracts the amount of gas left from the type of gas tank but when the next customer pumps gas the statistics get erased? any help would be appreciated, here is my code. keep in my mind this is part of a 5 class program and this is only one part.
import java.util.Random;
import java.util.Scanner;
public class GasPump
{
static Scanner Input = new Scanner (System.in);
private static double totalRevenue;
private static double currentPurchase;
//private int currentGasType;
private static double currentGasType;
private static double currentGasAmount;
private Client currentClient;
private int clock;
private static double regularTank;
private static double plusTank;
private static double supremeTank;
//private static double amountLeftInTank;
public void updatePump()
{
if (currentClient != null)
{
clock--;
if (clock == 0)
{
//totalRevenue += currentPurchase;
totalRevenue = totalRevenue + currentPurchase;
resetPump ( );
}
}
}
public void resetPump ( )
{
clock = 0;
currentClient = null;
currentPurchase = 0;
//currentGasType = "";
currentGasType = 0;
currentGasAmount = 0;
}
public boolean pumpOpen()
{
return (clock == 0) && (currentClient == null);
}
public static double getCurrentGasType()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
//Scanner Input = new Scanner(System.in);
System.out.println("What type of gas would you like?");
System.out.println("Regular , Plus or Premium");
System.out.println("1)Regular: $2.99 per gallon; 2)Plus: $3.99 per gallon; 3)Premium: $4.99 per gallon");
currentGasType = Input.nextDouble();
Random gen = new Random ();
//currentGasAmount = gen.nextDouble ()* 45;
currentGasAmount = gen.nextDouble()*50;
double roundOff = (double) Math.round(currentGasAmount * 100) / 100;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
if (currentGasType == 1)
{
currentGasType = 2.99;
regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
{
currentGasType = 3.99;
plusTank = plusTank - currentGasAmount;
}
else
{
currentGasType = 4.99;
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("# of gallons purchased: " + currentGasAmount);
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return currentGasType;
}
/*public static double getCurrentGasAmount() {
Random gen = new Random ();
currentGasAmount = gen.nextDouble ()* 50;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
System.out.println("# of gallons purchased: " + currentGasAmount);
return currentGasAmount;
}
*/
public static double getCurrentPurchase()
{
currentPurchase = currentGasType * currentGasAmount;
return currentPurchase;
}
public static double getTotalRevenue() {
totalRevenue += currentPurchase;
System.out.println("Total revenue so far is " + totalRevenue);
return totalRevenue;
}
/*public static double getAmountLeftInTank()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
if (currentGasAmount == 1)
if (currentGasType == 1)
{
//regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
else if (currentGasAmount == 2)
{
//plusTank = plusTank - currentGasAmount;
}
else
{
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return amountLeftInTank;
}
*/
public void serveAClient (Client aClient)
{
clock = 10;
currentClient = aClient;
GasPump.getCurrentGasType();
System.out.println("Your total is " + GasPump.getCurrentPurchase());
GasPump.getTotalRevenue();
//GasPump.getAmountLeftInTank();
/*
* design get methods
* ask client what type of gas he wants
* add more code here
*/
// add the total here
}
}
Don't use static fields for the data stored in GasPump.
static fields are singletons, they only have a single value shared across all instances of GasPump. This means that if you have multiple instances of GasPump, then calling reset will reset all of the gas pumps.
By removing the keyword static from each of the fields, then there will be a separate copy of the field held for each of the GasPump's. And thus calling reset will only wipe the fields for that one instance of GasPump.
The following diagram may help you to visualise the difference:
In this example, count has been shared across instances c1 and c2 of CircleWithCount.
You can read more detail about using the static keyword on fields here: What does the 'static' keyword do in a class?

How do I computer average into a method?

I'm attempting to call a method in order to calculate average (calcavgnow).. I'm trying to have it calculate the average of all the numbers in the array and return the average to the caller. I'm hoping it can deal with any size array. I tried attempting below.. can anyone help me figure out what I am doing wrong?
import javax.swing.JOptionPane;
public class sdasfs {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
calcavgnow = total / SelectNumber;
}
JOptionPane.showMessageDialog(null, getTotal(numbers) + " divided by " + Numbers.length + " is " + getAvg(Numbers));
}
//Create method in order to calculate calcavgnow
public static double getAvg(int numbers[]){
return (double)getTotal(numbers)/numbers.length;
}
public static int getTotal(int numbers[]){
int total = 0;
for(int i:numbers)
total +=i;
return total;
}
}// end class
Have a separate method to calculate average. Don't do everything inside the same method. Learn to modularize your code. So others can easily get adopt to your code.
public static double getAvg(double numbers[]){
return getTotal(numbers)/numbers.length;
}
public static double getTotal(double numbers[]){
double total = 0;
for(double i:numbers)
total +=i;
return total;
}
import javax.swing.JOptionPane;
public class AvgCalculator {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
}
calcavgnow = total / SelectNumber;
JOptionPane.showMessageDialog(null, "The average entered is " + calcavgnow);
}
}

Finding an average of a loop from a different method?

I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;

Categories