Population change over time - java

I'm having some problems with my program, i ask the user to enter the start population,daily growth in percent, and how many days they will multiply. Then calculate the end population for each day, while making sure they are constraints to the user entered data. I keep getting back the same results for each day and the constraints aren't doing their job either.
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
for (int days=0;days<=daysofIncrease+1;days++)
{
if (startPopulation>=2 || increase >0 || daysofIncrease>=1)
{
endPopulation=(startPopulation*increase)+startPopulation;
JOptionPane.showMessageDialog(null,"This is the organisms end population: "+endPopulation+" for day: "+days);
}
else
{
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
}
}
}
}

Your line
endPopulation=(startPopulation*increase)+startPopulation;
Will not calculate the end population correctly. You haven't used daysofIncrease at all.
I think you'll need to loop through the days. Note that I have not tested this, may need tweaking, but it should give you the idea:
double interimPopulation = startPopulation;
for (int days=1; days<=daysofIncrease; days++) {
interimPopulation *= (1.0 + (increase/100.0)); //get next day's population
}
endPopulation = interimPopulation;

I think you need to set somewhere in your loop this:
startPopulation = endPopulation;
And then you make another iteration of the loop.
Try this for example
endPopulation=(startPopulation*increase)+startPopulation;
startPopulation = endPopulation;
And if you don't want to lose the initial value of startPopulation,
just store it somewhere, before you change it (the way I suggest).

Related

Introducing an array to store scores in Java

The question I am working on is:
Write a program that:
asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).
Sample program behavior / output:
How many exams scores do you have to enter? 5
Enter score #1: 95.0
Enter score #2: 92.0
Enter score #3: 68.0
Enter score #4: 72.0
Enter score #5: 70.0
The average score is: 79.4
There are 2 scores larger than the average.
This is my code:
import java.util.Scanner;
public class testee {
public static void main(String[] args) {
int examnum = -1;
Scanner scan = new Scanner (System.in);
while (examnum<0) {
System.out.println("How many exam scores do you have to enter?");
examnum = scan.nextInt( );
}
for (int i=1; i<=examnum; i++) {
System.out.println("Enter score #" + i + ": ");
for (int a=1; a<=i; a++) {
a = scan.nextInt();
}
}
}
}
What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.
First prompt looks good however there is one small problem.
Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?
It's always nice to inform the User of any invalid entry.
To place items into an Array you need to declare that array and initialize it to the proper size:
int[] scoresArray = new int[examnum];
Think about this, where do you think this line of code should be placed?
Hint: You need to ensure that the required array size is already properly established.
Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?
Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).
If you want to add an element to your array, where do you think would be a great place in your code to do that?
Hint: int score = scan.nextInt(); scoresArray[i] = score;.
Things to consider:
When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?
Yes, you can nest while loops within a for loop and visa-versa.

I write a program but it misses something and I don't know how to take the rent from loop

A real estate office handles 50 apartment units. When the rent is $600 per
month, all the units are occupied. However, for each $40 increase in rent,
one unit becomes vacant. Each occupied unit requires an average of $27 per
month for maintenance. How many units should be rented to maximize the
profit?
Write a program that prompts the user to enter:
The number of apartment Units
The rent to occupy all the Units
The increase in rent that results in a vacant unit
Amount to maintain a rented unit
The program then outputs the number of units to be rented to maximize
the profit
but I want to show to the user the rent and I don't know how
import java.util.*;
public class yeungah {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
double rent, maintenance, maintenanceCost, increase;
double result=0, profit, maxProfit = 0;
int h=0, number;
System.out.println(" enter the number of apartment units: ");
number=input.nextInt();
System.out.println( " enter the rent value for all the occupied units: ");
rent=input.nextInt();
System.out.println("The increase in rent that results in a vacant unit: ");
increase=input.nextInt() ;
System.out.println( "enter the maintain value for each occupied unit: ") ;
maintenanceCost=input.nextInt() ;
for (int i = number; i > 0; i--, rent += increase)
{
result = i * rent ;
maintenance = i * maintenanceCost ;
profit = result – maintenance ;
if (profit > maxProfit)
{
maxProfit = profit ;
h =i ;
}
}
System.out.println( "Number of units to be rented in order to maximize profit is: "+maxProfit) ;
System.out.println("It occurs when Number of occupied Units is:"+h) ;
}
}
can anyone help?
Sadly I cant make comments yet but I'm curious.
When does the for loop end? I cant see that it ever reached i>0 since i is always decreasing and I cant see that i is changed in the for loop.
I would use a while loop that breaks when profit isn't larger then maxprofit.
In the end it should be enough to take number-h to answer the assignment question
Take everything I write with a grain of salt since I'm also a rookie. :)
To show the rent after each increase do System.out.println(rent) at the end of the for loop.
To show the rent at the end you would do the same thin after the loop.
A problem I'm seeing here is that you don't seem drop out of the loop once the max profit is found. I would recommend a boolean flag. Set it to false have it as a condition along with 1 > 0.
Then within the loop add an else to your if statement setting it to true.
This will cause the loop to drop out once the max profit is found.

I need the input of the user to not skip the value 100

I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}

Printing negative values in Java

My variables are
float amountLeft, amount;
char v1;
My goal is to let the user know If he uses more than a $1000 he will be in debt, the user can keep purchasing but he will be in debt. I can't get my head around negative numbers. How would I keep track of the negative numbers?
For example: "You just went over your limit. You owe us -5$ "
If you want to take a look at my code here it is.
amountLeft = 1000.0f;
while(amountLeft > 0) {
System.out.println(String.format("%3s %,1.2f %3s", "You have" , amountLeft, "money remaining to spend."));
System.out.println("Enter the cost of the item you want buy");
amount = new Scanner(System.in).nextFloat();
System.out.println("are you sure you wanna purchase this item?");
v1 = keyboard.next().charAt(0);
if (v1 == 'y')
{
amountLeft = amountLeft - amount;
System.out.printf("%.2f",amountLeft);
You can to create a situation that allows that user to spend if he is negative if (amountleft < 0)
Also, that loop should be while (amount >= 0) because the user won't owe anything if he is at 0 dollars.
Simply add a new statement inside your amount left:
if (amountLeft < 0) {
// alert user that hes over the amount
}
Add this at the end of your code, and then you can print his negative amount every type the loop is executed.
You can then print the amount as per normal.
Variables can start at positive, and end at negative, or go from positive, to negative, to positive with no dramas.
Let me paraphrase your question. You want to let the user buy stuff even though his/her money is not enough. And each time he/she does that, you print "you owe us $xxx". But now you are printing "you owe us $-xxx". You basically want the negative number to be printed out as a positive number, right?
The other answers tell you how to check for negative value but you are actually asking how to print negative values as positive ones.
There is a method for this in the java.lang.Math class! You can print -5 as a positive number this way:
System.out.println ("You owe us $" + Math.abs(amountLeft));

Getting trouble with picking most and less valued day from an array

I have this piece of code, array of 7 days, the user enter which day and how many tickets per day.
the loop will continue untill the number is greater than 50(of total tickets).
I want to pick the most wanted day, and the less one.
This is the code:
int ticketCounter=0;
final int MAX_TICKET=50;
int[] dayOfTicket=new int[7];
int mostWantedDay=dayOfTicket[0];
int LessWantedDay=dayOfTicket[0];
int indexOfWantedDay=0;
int indexOfLessWantedDay=0;
while(ticketCounter<=MAX_TICKET){
System.out.println("Enter the day number (1-7) and the number of tickets:");
int whichDay=s.nextInt();
int numberOfTicket=s.nextInt();
if(whichDay>0 && whichDay<8){
dayOfTicket[whichDay-1]+=numberOfTicket;
ticketCounter+=numberOfTicket;
}else{
System.out.println("Invalid input.\n");
}
}
}
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f+1;
}
System.out.printf("The day with max tickets is: %d \nThe day with min tickets is: %d \n\n",indexOfWantedDay, indexOfLessWantedDay);
it is picking wrong most wanted day, and always print 0 as less wanted day.
I have some problems with this checking method on the last for loop.
I will aprriciate your help.
thanks
EDIT: I took out the for loop outside the WHILE ( it was my copy paste mistake)
Part of the problem is when you initialize LessWantedDay, you initially set it to 0.
Initialize this value to the maximum possible by using
int LessWantedDay=Integer.MAX_VALUE;
Furthermore, you need to update the logic within your check to filter out 0's (assuming you want to print a day that doesn't have 0 tickets), and to update your max/min values as you parse the dayOfTicket array.
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
mostWantedDay = dayOfTicket[f];
}
if(dayOfTicket[f]<LessWantedDay && dayOfTicket[f] > 0){
indexOfLessWantedDay=f+1;
LessWantedDay = dayOfTicket[f]
}
}
Tested output:
Enter the day number (1-7) and the number of tickets:
1 10
Enter the day number (1-7) and the number of tickets:
3 5
Enter the day number (1-7) and the number of tickets:
5 20
Enter the day number (1-7) and the number of tickets:
4 15
Enter the day number (1-7) and the number of tickets:
6 10
The day with max tickets is: 5
The day with min tickets is: 3
This code is almost completely correct.
In your loops, where you say:
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f+1;
}
}
You should not set the index to "f+1", that would be the index after where we are in the loop, and we want where we actually are.
Also, this will overwrite the highest day with the last day that is more than the variable "mostWantedDay" and vise versa for "lessWantedDay. What you need to do is after you find a number of tickets that is higher than your current high, or lower than your current low, set it to that.
This way, when testing, you test against the highest or lowest one yet. As of right now, you are continuously testing against the first index's number because that is stored in most/lessWantedDay and is never changed.
After changes, your code will look like:
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f;
mostWantedDay = dayOfTicket[f];
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f;
LessWantedDay[f] = dayOfTicket[f];
}
}
The reason your less wanted day is always printing 0 is because that's most likely lower than the input being entered in.
An alternative would be to set the lessWantedDay value to INTEGER.MAX_VALUE, or just the max ticket value, or another arbitrary random large number, like 9001, 100000, something like that.
An alternative alternative (in case you can't use a basic thing mentioned above) is that you can set the LessWantedDay and mostWantedDay to be the first element of the array after you get the input from the user.
int mostWantedDay;
int LessWantedDay;
<snipped out input logic/>
mostWantedDay = dayOfTicket[0];
LessWantedDay = dayOfTicket[0];
Whenever you find a most and least day, you need to update the values of mostWantedDay and LessWantedDay with the values you found
so your if statements would look like this:
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
mostWantedDay = dayOfTicket[f];
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f+1;
LessWantedDay = dayOfTicket[f];
}

Categories