I'm quite new to programming. I'm trying to make a program for a bike rental service. And the issue is that there are two tariffs (1 and 2) for a specific time.
Tariff 1 : 00:00 to 07:00 and 17:00 to 24:00. (1$)
Tariff 2 : 07:00 to 17:00. (2$)
I need to use the scanner, so I write the two numbers, and it must calculate me the number of hours in tariff 1 and tariff 2, as well as the total cost. The issue is that I have no idea how to write the program so it detects how much hours are the in one tariff or another.
The program must work the following way :
Input 1
Input 2
Calculate the amount of hours in Tarif 1 and 2, and give a total.
Give the total price.
So here's the code :
import java.util.Scanner;
public class Bike {
public static void main(String[] args) {
Scanner clavier = new Scanner(System.in);
System.out.print("Give the starting hour : ");
int start = clavier.nextInt();
System.out.print("Give the ending hour : ");
int finish = clavier.nextInt();
if (start < 0 || start > 24) {
System.out.println("Hours must be within 0 and 24 !");
}
if (start == finish) {
System.out.println("Strange, you didn't take it long enough !");
}
if (start >= 24 || start > finish) {
System.out.println("Strange, the starting hour is after the end ...");
}
int total = finish - start;
if (total > 0) {
System.out.println("You have rented the bike for " + total + " hours.");
}
//This is where it becomes complicated.
if ((start >= 0 && start < 7)||(start >= 17 && start <= 23)) {
System.out.println("Amount of hours in Tariff 1 is : " + ((7 - start) +(finish - 17)));
} else {
System.out.println("Amount of hours in Tariff 2 is : "
System.out.print("Total amount to pay is : ");
System.out.println(" dollars.");
{
}
Ok, you're new to programming so I'm going to try and keep this simple. The issue here isn't syntax or some secret in java, its just missing logic. I can see from what you've written that you're either in high/middle school just starting programming or someone who has just started learning to code.
So I'm going to try and keep it simple and not give you too many hints.
You cannot have tariff 2 only in the else. I would recommend creating 2 ints, tariffOne and tariffTwo (or whatever names you like),make them = 0. Calculate them using some if statements. Then, when you have the values use them in the System.out.
This is good because you can add simply add whatever you want to the ints and you will always have their values.
The reason this question is being downvoted is because you've got all the tools to answer the question and you've just not got a grasp of the logic required, its not generally good practice to do this since it seems lazy, even if you've tried really hard.
Related
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'm in the process of making a program using input from a text file, it only has 2 lines of text in it which is
120 (this is the time)
2 (this is changes)
My code is meant to read the user's input which converts hours to minutes, and then asks for a number of changes. If the hours entered are 02:00 which is 120 minutes and the changes entered are 2 or less then it will come back saying 'acceptable', and if not it will read 'unacceptable' however I am having a bit of trouble formulating this. If anybody could provide assistance I would appreciate it greatly!
Code to follow:
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) throws IOException{
final Scanner S = new Scanner(System.in);
final Scanner inFile = new Scanner(new FileReader("task.txt"));
// open file and associate objects
int IOminutes = Integer.parseInt(inFile.next());
int changes = Integer.parseInt(inFile.next());
// close the input file
inFile.close();
System.out.print("Specify Time (HH:MM): ");
String givenTime = S.next();
System.out.print("Specify Changes: ");
String givenChanges = S.next();
// save the index of the colon
int colon = givenTime.indexOf(':');
// strip the hours preceding the colon then convert to int
int givenHours = Integer.parseInt(givenTime.substring(0, colon));
// strip the mins following the colon then convert to int
int givenMins = Integer.parseInt(givenTime.substring(colon + 1, givenTime.length()));
// calculate the time's total mins
int mins = (givenHours * 60) + givenMins;
// using given time
System.out.println(givenTime + " = " + mins + " minutes");
if (!givenTime.equals(IOminutes) && changes >= 3) {
System.out.println("Time: " + givenTime + ", Changes: " + givenChanges + " = unacceptable!");
} else if (givenTime.equals(IOminutes) && changes <= 2) {
System.out.println("Time: " + givenTime + ", Changes: " + givenChanges + " = acceptable!");
}
S.close();
}
}
Your inputs (file-based and user-based) look reasonable.
By the time you reach your if-elseif logic on line 40, you have the following values (all values based on the problem description in the question):
loaded from "task.txt"...
IOminutes: 120
changes: 2
user input:
givenTime="02:00"
givenChanges=2
givenHours=2
givenMins=0
mins=2*60+0 = 120
Your conversion from strings to integers looks like no problem.
Your desired outcome of "acceptable" / "unacceptable" is hard for me to understand; not what it is doing, but Why it is doing that.
I'm having trouble understanding why you have two "changes".
This would make more sense to me if you just had:
task.txt: IOminutes=120, changes=2
given: time="hh:mm"
Now compute difference (in minutes) between task.txt's IOminutes and user's given time. Let's call that difference givendiff. Then you have something like:
if givendiff > changes then unacceptable.
Examples (user input values more or less made up):
task.txt: IOminutes=120, changes=2
test 1: given time="02:00" (computed givendiff=0, so acceptable)
test 2: given time="01:50" (computed givendiff=-10, so unacceptable)
test 3: given time="02:05" (computed givendiff=5, so unacceptable)
test 3: given time="02:02" (computed givendiff=2, so acceptable)
test 3: given time="01:58" (computed givendiff=-2, so acceptable)
I would encourage you to review the original requirements and verify whether your user is supposed to be give you an extra "changes" in addition to task.txt's changes. Or if you're supposed to compute a the difference between task.txt's IOminutes and the user-entered value, and complain if that difference exceeds task.txt's changes value.
I would go further but this seems like a homework or code-challenge problem; if so, hopefully this is enough to help nudge your perspective to re-thing what "changes" means in the original requirements. Good luck.
Link to challenge can be found here
Problem Statement
Tieu owns a pizza restaurant and he manages it in his own way. While
in a normal restaurant, a customer is served by following the
first-come, first-served rule, Tieu simply minimizes the average
waiting time of his customers. So he gets to decide who is served
first, regardless of how sooner or later a person comes.
Different kinds of pizzas take different amounts of time to cook.
Also, once he starts cooking a pizza, he cannot cook another pizza
until the first pizza is completely cooked. Let's say we have three
customers who come at time t=0, t=1, & t=2 respectively, and the time
needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies
first-come, first-served rule, then the waiting time of three
customers is 3, 11, & 16 respectively. The average waiting time in
this case is (3 + 11 + 16) / 3 = 10. This is not an optimized
solution. After serving the first customer at time t=3, Tieu can
choose to serve the third customer. In that case, the waiting time
will be 3, 7, & 17 respectively. Hence the average waiting time is (3
+ 7 + 17) / 3 = 9.
Help Tieu achieve the minimum average waiting time. For the sake of
simplicity, just find the integer part of the minimum average waiting
time.
Input Format
The first line contains an integer N, which is the number of
customers. In the next N lines, the ith line contains two space
separated numbers Ti and Li. Ti is the time when ith customer order a
pizza, and Li is the time required to cook that pizza. Output Format
Display the integer part of the minimum average waiting time.
Constraints
1 ≤ N ≤ 10^5
0 ≤ Ti ≤ 10^9
1 ≤ Li ≤ 10^9
Note
The waiting time is calculated as the difference between the time a
customer orders pizza (the time at which they enter the shop) and the
time she is served.
Cook does not know about the future orders.
I've been at this for several hours.
I'm pretty sure my problems has to do with the way I increment the total Wait time.
Any help would be much appreciated.
code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
MinimumAverageWaitingTime mawt = new MinimumAverageWaitingTime();
while(n-- > 0) mawt.insert(s.nextLong(), s.nextLong());
System.out.print(mawt.calculateAverageWaitingTime());
}
}
class MinimumAverageWaitingTime {
private PriorityQueue<e_time_p_time> incomingOrders = new PriorityQueue<>(10, new Comparator<e_time_p_time>(){
//Order by the customerWaitTime ASC
#Override public int compare(e_time_p_time w, e_time_p_time w1) {
return (int) (w.entryTime - w1.entryTime);
}
});
private PriorityQueue<e_time_p_time> awaitingOrders = new PriorityQueue<>(10, new Comparator<e_time_p_time>(){
//Order by the difference between entrytime and pizzaCookTime ASC
#Override public int compare(e_time_p_time w, e_time_p_time w1) {
return (int) (Math.abs(w.entryTime - w.pizzaCookTime) - Math.abs(w1.entryTime - w1.pizzaCookTime));
}
});
private long total = 0l;
public void insert(long customerWaitTime, long pizzaCookTime) {
incomingOrders.add(new e_time_p_time(customerWaitTime, pizzaCookTime));
}
public long calculateAverageWaitingTime() {
int size = incomingOrders.size();
e_time_p_time currentOrder = null;
e_time_p_time laterOrders = null;
while(incomingOrders.size() > 0) {
//Start by getting the customer that has the earliest arrival time (the queue is sorted that way)
currentOrder = incomingOrders.remove();
//Calculate it's waiting time.
total += currentOrder.entryTime + currentOrder.pizzaCookTime;
do {
/*Move all the customers that entered the shop while the current pizza is in the oven
to the awaitingOrders orders queue*/
laterOrders = incomingOrders.remove();
awaitingOrders.add(laterOrders);
} while (currentOrder.pizzaCookTime >= laterOrders.entryTime && incomingOrders.size() > 0);
//Go through awaitingOrders queue and calculate waiting time for the remaining orders
//(The queue is sorted as the difference between entrytime and pizzaCookTime ASC)
while(awaitingOrders.size() > 0) {
e_time_p_time shortestOrder = awaitingOrders.remove();
long waitTimeBeforeCooking = Math.abs((shortestOrder.entryTime + shortestOrder.pizzaCookTime) - currentOrder.entryTime);
total += waitTimeBeforeCooking;
}
}
//It's supposed to be the average time, but first I need the total to be correct, and right now, it's not...
System.out.println("\nTotal waiting time: ");
return total;
}
private static class e_time_p_time {
private long entryTime;
private long pizzaCookTime;
e_time_p_time(long entryTime, long pizzaCookTime) {
this.entryTime = entryTime;
this.pizzaCookTime = pizzaCookTime;
}
}
}
In this code:
do {
/*Move all the customers that entered the shop while the current pizza is in the oven
to the awaitingOrders orders queue*/
laterOrders = incomingOrders.remove();
awaitingOrders.add(laterOrders);
} while (currentOrder.pizzaCookTime >= laterOrders.entryTime && incomingOrders.size() > 0);
A couple of things seem wrong here:
You always add at least one item to awaitingOrders - but what if no-one enters the shop while the current pizza is in the oven? (e.g. for the last pizza)
You compare the pizzaCookTime - e.g. ten minutes, with the entryTime, e.g. 4pm. This doesn't seem right - shouldn't you compare the time that the pizza is completed with the entryTime?
I've created a program that allows a user to enter in Journal entries (up to 7 days) and then allows a person to call up one of those days after they enter in an entry. Unfortunately, this has left me with some weird string error that I'm not familiar with.
Code as follows:
public class eDiary{
public static void main (String args[]){
int[] days = new int[7];//get our days
days[0] = 1;//start with 1 and not 0
days[1] = 2;
days[2] = 3;
days[3] = 4;
days[4] = 5;
days[5] = 6;
days[6] = 7;
String [] events = new String[7];//events for the days
int i = 0;
//asks for input and counts
for(i=0; i<7; i++){
String event = Console.readString("Tell me the major event of day " + days[i] + "\n");
events[i] = event;
}
int journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
while (journal_entry != 0) {
System.out.println(events);
journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
//get r dun!
The input and output:
Tell me the major event of day 1
one
Tell me the major event of day 2
two
Tell me the major event of day 3
thre
Tell me the major event of day 4
four
Tell me the major event of day 5
five
Tell me the major event of day 6
six
Tell me the major event of day 7
seven
Enter what day you want to hear or Enter 0 to stop
1
[Ljava.lang.String;#10181f5b
Enter what day you want to hear or Enter 0 to stop
0
Howdy y'all!
Thanks a lot for the quick responses. One thing it seems to be doing now is when replacing
System.out.println(events);
with
System.out.println(events[journal_entry]);
Now gives me input such as this:
Tell me the major event of day 1
first day
Tell me the major event of day 2
second day
Tell me the major event of day 3
third day
Tell me the major event of day 4
fourth day
Tell me the major event of day 5
fifth day
Tell me the major event of day 6
sixth day
Tell me the major event of day 7
seventh day
Enter what day you want to hear or Enter 0 to stop
1//the day im asking for
second day//spitting out the next day's entry instead of the first day's entry
Enter what day you want to hear or Enter 0 to stop
0//this is me stopping it
It's not an error.
System.out.println(events);
In this line you are trying to print the array, but that statement doesn't print the array contents, it only prints the object class name followed by its hashcode.
To print the array content you have to use
System.out.println(Arrays.toString(events));
Or, if you want, loop through the array and print its values
The [Ljava.lang.String;#10181f5b stuff is what you get when you explicitly or implicitly call Object.toString() and the target object's class doesn't override toString(). In this case, the issue is that Java array types do not override toString().
If you want to output an array, use java.util.Arrays.toString(...) to convert it to a String, then output that.
But in this case, you actually need to output a specific entry, not the entire array. The fix is to change
System.out.println(events);
to
System.out.println(events[journal_entry]);
For the record, the stuff above consists of the classes internal name ("[Ljava.lang.String;") and the object's identity hashcode (in hexadecimal).
This is not a "weird error string".
The output you are getting is because:
In Java, each object has toString() method, the default is displaying the class name representation, then adding # and then the hashcode.
You should use Arrays#toString(), which is implemented this way:
3860 public static String toString(int[] a) { {
3861 if (a == null)
3862 return "null";
3863 int iMax = a.length - 1;
3864 if (iMax == -1)
3865 return "[]";
3866
3867 StringBuilder b = new StringBuilder();
3868 b.append('[');
3869 for (int i = 0; ; i++) {
3870 b.append(a[i]);
3871 if (i == iMax)
3872 return b.append(']').toString();
3873 b.append(", ");
3874 }
3875 }
This will help you to better understand arrays.
Of course you can manually loop on the array and print it:
for(String event: events) {
System.out.println(event);
}
There is nothing wrong and that's not an error message.
Instead, it's the string representation of an array. Consider this line:
System.out.println(events);
You are printing the whole array, so you get that representation -- which happens to be a bit ugly, indeed. You want to print only one element, the one corresponding to the selected day. Use:
System.out.println(events[journal_entry]);
And perform bound checks.
This is not an error. You want to print the value of variable events. [Ljava.lang.String;#10181f5b means that events is an array of type java.lang.String and 10181f5b is hashcode of this variable. What you want to println is event[i] where i is the number of a day.
In java array's are consider as object. you are printing the event array object that's not what you want.
You need to print name of the day in a week. You need to replace
System.out.println(events);
to
System.out.println(events[journal_entry]);
It won't print out the answer correctly because you just pointed System.out.println() to events which is supposed to be an array pointer and not the actual variable. You should just replace this line with
System.out.println(events[journal_entry]);
For it to make sense. Run it with the conmmand and see if it will run properly.
Thanks for all the responses! I was able to resolve the issue. Here's the code if anyone is curious:
public static void main (String args[]){
int[] days = new int[7];//get our days
days[0] = 1;//start with 1 and not 0
days[1] = 2;
days[2] = 3;
days[3] = 4;
days[4] = 5;
days[5] = 6;
days[6] = 7;
String [] events = new String[7];//events for the days
int i = 0;
//asks for input and counts
for(i=0; i<7; i++){
String event = Console.readString("Tell me the major event of day " + days[i] + "\n");
events[i] = event;
int journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
while (journal_entry != 0) {
System.out.println("On day " + days[i = 0] + " " + events[journal_entry - 1]);
journal_entry = Console.readInt("Enter what day you want to hear or Enter 0 to stop \n");
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).