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

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];
}

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.

Random Number with Java in Android Studio

i'm try to make a random or unique code to payment method, for example the user must pay for Rp. 10.000 and then the user checkout and the system give the total payment with unique code in last three number.
For example user should pay for Rp. 10.000 and then the system showing Rp. 10.123
for other example, user pay for 1.000.000 and then system showing the total is 1.000.562 just unique or random in last three number
how i can make like this in java for android ?
UPDATE
i've been try this code
int someNumber = 10.000;
int lastThree = someNumber % 1000;
but when the last 3 number is '0' it return 0, when i'm change the last 3 number like 10.234 it return into 234, now how i can get the last three number when the value is like 10.000
That's because your 'lastThree' is an integer and there is no way to have an integer like 000. if you need last three number, you can use something like this:
int someNumber = 10.000;
String temp = Integer.toString(someNumber);
String lastThree = temp.substring(temp.length() - 3);
Now if you pass 10000, lastThree will be '000'.

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.

Using a loop, and conditionals to change score in a game

I used a loop to generate 1 numbers onto the text file. I start to have problems on when the user starts to play the game.
I'm going to go right ahead and give my pseudo code so you can understand what I want to do...
Randomly generate 10 numbers between 0 and 10
Store these numbers into a file called mysteryNumbers.txt, a number per line
Prompt the user to enter a number between 0 and 10
Check this number against the first number in the file
If the user guesses right, subtract 10 from the score (at the start, the score is 0)
If the user guesses wrong, add the correct amount of score to the current score of the user (at the start, the score is 0)
Prompt the user to enter a number between 0 and 10
Check this number against the second number in the file
If the user guesses right, subtract 10 from the score
If the user guesses wrong, add the correct amount of score to the current score of the user
Prompt the user to enter a number between 0 and 10
Check this number against the third number in the file
If the user guesses right, subtract 10 from the score
If the user guesses wrong, add the correct amount of score to the current score of the user
… etc. …
Display the score of the user: of course, the lower the better!
-I also organized the code below following the pseudocode outline.
/************************************************************************************
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//numbers are now generated onto text file...
/************************************************************************************
* 3. Prompt the user to enter a number between 0 and 10 */
Scanner myscnr= new Scanner (System.in);
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
/************************************************************************************
* 4. Check this number against the first number in the file */
// to check the user's number against the file's, you need to be able to read
// the file.
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
/************************************************************************************
* 5. If the user guesses right, subtract 10 from the score */
/************************************************************************************
* 6. If the user guesses wrong, add the correct amount of score to the current *
* score of the user (at the start, the score is 0 */
/************************************************************************************
* 7. Prompt the user to enter a number between 0 and 10 */
//Sytem.out.println ("Enter a number between 0");
/************************************************************************************
* 8. Check this number against the second number in the file */
etc etc...
I'm confused starting on comment section 5. I know I have to create a new integer for score, but after that I'm lost!
I tried working in an if else statemnent but I couldn't get it going..
I guess you created the 10 random numbers and stored in the file without problem.
It would be easier for the rest your code to have the numbers in an array. You could store them in sequence obviously. Next create a for loop to get input number and check against the corresponding number in the array .
Ex:
Considering you have the array numbers[] containing your numbers.
for(int i=0;i<10,i++){
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if(userNumber==numbers[i])
score-=10;
else
score++; //the addition you wanna make
}

Population change over time

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).

Categories