I am a beginner coder using Netbeans Java. I have created a code that initially asks how many gallons are in your gas tank. Then, it will have a while loop asking how many miles you will be traveling for this first run and how fast are you traveling. This will repeat with a while loop until you input '0' to stop adding trips. I am stumped on how to convert this while loop into only using For loops. I would greatly appreciate the assistance. Here is my code that has while loops.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tank;
double miles;
double speed;
double totalMiles = 0.0;
int choice;
double time;
double totalTime = 0.0;
double fuelConsumption;
System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
tank = input.nextInt();
System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");
System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
choice = input.nextInt();
while (choice == 1)
{
System.out.print("How many miles are you traveling? "); // miles
miles = input.nextFloat();
System.out.print("What is your speed for this run (MPH)? "); // speed
speed = input.nextInt();
System.out.print("\n");
totalMiles = totalMiles + miles;
time = (miles/speed);
totalTime += (time*60);
fuelConsumption = (20*(tank/totalMiles));
System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? "); // asking another leg
choice = input.nextInt();
if (choice == 0)
{
System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
+ "You traveled a total of about ", totalMiles , " miles.");
System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");
if (fuelConsumption >= 2)
{
System.out.println("Your car has enough gas to return.");
break;
}
else
{
System.out.println("Your car will need more gas to return.");
break;
}
}
}
}
}
That is not a use case for a for loop, where we iterate over a known number of elements for do a known number of iterations. Like, repeat 10 times or such.
Technically it can be solved with a for loop, but that is abusing the concept a bit. The while loop is a perfect fit for that task.
This is not a place to use a for-loop, you use a for loop for something like this:
printAmount = 10;
for (int i = 0; i < printAmount; i++) {
System.out.println("Hello World");
}
Here you are using the for loop to print "Hi" for the amount in printAmount.
Your case is different: You want the while-loop to repeat while the input is "1" so you use a WHILE-loop.
Related
I'm sorry, I know this question is probably asked a million different times every day, but I truly can't find the answer I'm looking for. I'm a beginner in Java (I'm in college and learning a bunch of new languages), and my while loop is printing out the same thing every time.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is the loan amount? ");
int amount = scanner.nextInt();
int x = 1;
//your code goes here
while (x < 6){
System.out.println("Month " +x+ ":");
int percent = (amount / 10);
System.out.println("Payment: 10 percent of " +amount+ " = " +percent);
int rAmt = amount - percent;
System.out.println("Remaining amount: " +rAmt);
x++;
}
}
}
So the issue is that you never actually change amount after doing your calculations inside the while loop. What I think you want to do, is to set amount = rAmt;, which would produce the following code. This will cause the amount to be decreased by 10% each iteration, and this new value carried forward.
...
//your code goes here
while (x < 6){
System.out.println("Month " +x+ ":");
int percent = (amount / 10);
System.out.println("Payment: 10 percent of " +amount+ " = " +percent);
int rAmt = amount - percent;
System.out.println("Remaining amount: " +rAmt);
amount = rAmt;
x++;
}
...
I'm trying to create a program that simulates driving a car. In my program, I have the following loop to allow the user to "drive" however many miles they wish:
public void run() {
do {
System.out.println("How many miles would you like to drive?");
int userInput = scanner.nextInt();
if (userInput > 360) {
System.out.println("You don't have enough fuel to drive that far! Please try again.");
run();
}
System.out.println("You are driving: " + userInput + " miles.");
try {
for(int c = 0; c < parts.size(); c++){
parts.get(c).function(userInput);
}
} catch (BreakdownException e) {
}
} while (getBoolean("Keep driving?"));
I would like to take the userInput variable and save it so that I can keep track of how many miles are in the gas tank. This is the code I currently have for that:
public void function(int milesDriven) throws BreakdownException {
int mpg = 30;
int gallons = 12;
int totalMiles = gallons * mpg;
int milesLeft = totalMiles - milesDriven;
if(milesLeft <= 0) {
throw new BreakdownException("You ran out of fuel!");
} else if (milesLeft <= (totalMiles / 4)) {
if (getBoolean("You are low on fuel! Refuel?")) {
milesLeft = gallons * mpg;
System.out.println("You now have enough fuel to travel " + totalMiles + " miles.");
}
} else {
System.out.println("You now have enough fuel to travel " + milesLeft + " miles.");
}
}
Currently, each time the loop in the first code block runs, the value for milesDriven in the second code block resets. Thus, every time the user "drives", their gas tank automatically refills. Is there a way I can store the userInput value so that it retains between loops?
Thanks!
If you don't want to change things up too much, one easy way would be to simply accumulate the user input with another variable, and pass that value into the function method instead of the user input that updates on each loop. So for example, outside of the do-while loop you would have:
int milesDriven = 0;
Then, each time the user gives a new input, add that value to the miles driven:
int userInput = scanner.nextInt();
milesDriven += userInput;
And finally pass that value into the function method instead of the user input:
parts.get(c).function(milesDriven);
This is for an assignment in my class. It is to make an automatic ordering system. I'm still new to Java so everything doesn't necessarily click just yet. I think most things work for the most part but the main thing I am having trouble with is making the loop itself and making an exit for it.
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
while (itemnumber < 1 || itemnumber > 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double total = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber){
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Price Total: " + total);
}
This is my first time posting on this site, but I think I found your problem. There are two large errors, indicated by the arrows:
while (itemnumber >= 1 || <-- itemnumber <= 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
} <--
1) This should be a '&&' not a '||'. You want it to be within the range. Right now the number it reads has to be greater than or equal to 1 OR less than or equal to 4, which is all integers.
2) You close your loop prematurely. What your code does right now (after the && switch) is it takes numbers 1-4 and keeps repeating the "Enter the item number...." line until you put a number not in the range, then it continues.
The fix: there are a few ways to fix this. My fix would be thus, and the explanation will come after:
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
double total = 0;
while (itemnumber >= 1 && itemnumber <= 4) {
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber)
{
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print("Price Total: " + total);
}
}
Explanation: In essence, you had like 90% of it. I moved the mentioned '}' to the end here:
itemnumber = userInput.nextInt();
} <--
That way, it loops over this code until the user ends.
Additionally, your loop does not need much fixing. It can be used with the && fix. However, you have to put that top line before the loop.
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
And then you put the same line at the end of the loop to reset itemnumber. What your loop does is if itemnumber is between 1 and 4, it executes the following code. Otherwise, it stops. By checking before you enter the loop, you set itemnumber so that way the loop has something to check. And you put the next input at the end of the loop so that way your program finishes totaling its first execution before moving on to the next.
Additionally, you should move the variable 'total' out of the loop as seen above. If you keep looping over it and resetting it to 0, your total will output 0 every time. Best to keep the creation of total out of the loop, and its modification inside the loop.
Small tip, use System.out.println(); instead of System.out.print(); it puts the outputs on its own line. Looks a little nicer.
I think that covers it. If you want more explanation, I'd be more than happy to give it to you. Java is pretty fun once you get used to it. It just takes time. :D
When I run this code, which is a menu with many different options. it consists of many loops. Some of which I have yet to make. I am having trouble with my coin toss simulator. Although I have a for loop, the loop only cycles through once instead of until the user selects "0" to exit the program and return to the main menu but also my other problem is that the simulator wont return to the main menu if 0 is selected. What is going on??? here is an example of my troubles.
Enter seed value: 3
===== CS302 TOOL BOX =====
T > COIN TOSS SIMULATOR
G > GRADE ESTIMATOR
C > COLOR CHALLENGE
Q > QUIT
Type code letter for your choice: t
COIN TOSS SIMULATOR
Enter 0 to quit. How many tosses?
4
3.0 heads and 1.0 tails means 75.0% were heads
Then the simulator doesn't ask "enter 0 to quit. How many tosses?" again. in fact if I press another number, say 3 I'd get this. Also zero doesn't end the simulator and prompt the main menu again.
3 is not a valid choice.
===== CS302 TOOL BOX =====
T > COIN TOSS SIMULATOR
G > GRADE ESTIMATOR
C > COLOR CHALLENGE
Q > QUIT
System.out.println("");
System.out.println( "===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{
Scanner anotherScanner = new Scanner(System.in);
boolean usersSelection = false;
String c;
while (!usersSelection)
{
{
System.out.print(""+ "Type code letter for your choice: ");
}
if (anotherScanner.hasNext("q|Q"))
{
c = anotherScanner.next();
usersSelection = true;
System.out.println(""
+ ""
+ "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")){
c = anotherScanner.next();
usersSelection = true;
System.out.println("");
System.out.println("COIN TOSS SIMULATOR");
System.out.println("");
System.out.println("Enter 0 to quit. How many tosses?");
Random rand = new Random();
Scanner insideScanner = new Scanner(System.in);
int feeble = insideScanner.nextInt();
double heads = 0;
double tails = 0;
boolean headsvsTails;
headsvsTails = rand.nextBoolean();
for (int i =0; i < feeble; i++)
{
headsvsTails = rand.nextBoolean();
if (headsvsTails == true){ heads++;}
else {tails++;}
}
System.out.println(heads + " heads and " + tails + " tails means " + (heads/(heads+tails)*100 + "% were heads"));
}
if (anotherScanner.hasNext("g|G"))
{
c = anotherScanner.next();
usersSelection = true;
System.out.println("");
System.out.println("GRADE ESTIMATOR");
Scanner gradeE = new Scanner(System.in);
double exam1;
double possiblePts;
double programPts;
double programPossible;
double avg;
double avge;
double avrg;
System.out.print("Enter exam points earned (int): ");
exam1=gradeE.nextDouble();
if (exam1<0)
{System.out.print("Enter exam points earned (int): ");
exam1=gradeE.nextDouble();}
System.out.print("Enter exam points possible (int): ");
possiblePts=gradeE.nextDouble();
if (possiblePts<0) {System.out.print("Enter exam points possible (int): ");
possiblePts=gradeE.nextDouble();}
System.out.print("Enter program points earned (int): ");
programPts=gradeE.nextDouble();
if (programPts<0) {System.out.print("Enter program points earned (int): ");
programPts=gradeE.nextDouble();}
System.out.print("Enter program points possible (int): ");
programPossible=gradeE.nextDouble();
if (programPossible<0) {System.out.print("Enter program points possible (int): ");
programPossible=gradeE.nextDouble();}
avge = exam1+programPts;
avrg = possiblePts+programPossible;
avg = avge/avrg*100;
if (avg<60)
System.out.println("Grade estimate for " +avg+ "% is a F");
else if (avg<70)
System.out.println("Grade estimate for " +avg+ "% is a D");
else if (avg<80)
System.out.println("Grade estimate for " +avg+ "% is a C");
else if (avg<90)
System.out.println("Grade estimate for " +avg+ "% is a B");
else if (avg>=90)
System.out.println("Grade estimate for " +avg+ "% is a A");
}
Alright buddy there is a lot wrong with your code. You constantly declare new Scanners. Spacing is inconsistent and portions of your code are separated from each other by a sea of white space the span of the Pacific Ocean.
Here is a fix:
if (anotherScanner.hasNext("t|T")){
c = anotherScanner.next();
usersSelection = true;
System.out.println("");
System.out.println("COIN TOSS SIMULATOR");
System.out.println("");
System.out.println("Enter 0 to quit. How many tosses?");
Random rand = new Random();
Scanner insideScanner = new Scanner(System.in);
int feeble = insideScanner.nextInt();
double heads = 0;
double tails = 0;
boolean headsvsTails;
headsvsTails = rand.nextBoolean(); // This is Worthless
while ( feeble != 0 ) { //Pay attention to this while loop
for (int i =0; i < feeble; i++) {
headsvsTails = rand.nextBoolean();
if (headsvsTails == true){ heads++;}
else {tails++;}
}
System.out.println(heads + " heads and " + tails + " tails means " + (heads/(heads+tails)*100 + "% were heads"));
System.out.println("Enter 0 to quit. How many tosses?"); //I ask the question again
heads = 0;
tails = 0;
feeble = insideScanner.nextInt();//I get new input
}
}
The key here is the while loop. I use your feeble variable as its condition. It will run so long as the user does not provide a 0.
Please take some time to walk a friend or a professor through your code. Explain it to them, encourage them to ask questions.
Also I consider it mandatory to read this. Don't be discouraged. When I look at the code I wrote 3 years ago it looked a lot like this. You will get better.
*fixed code so heads/tails is not additive based on input from comments.
Question Answered: Thank you everyone for the help!!!
i'm having a bit of trouble with finishing my code mainly because I'm really new to coding, but nonetheless I'm still trying. Any help is greatly appreciated!
I have 3 problems:
My main problem is that i do not understand how to get my code to add all the totals from each loop.
Also, after the loop starts it won't end when I enter '0' anymore, but if i end the loop when i first run the loop it will work.
Finally, how do i make the decimal total to show up in this format; xx.xx rather than xx.xxxxxxx?
Thank you in advance, i really appreciate any help
import java.util.Scanner;
public class takeOrders {//Find totals and average price
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int euro; // what country the candy canes are from
int us;// what country the candy canes are from
int holder; //place holder for user input of location
int v110 = 0; //110v
int v240 = 0; //240v
int sum = 0, i = 1;
double total = 0;
double discount = 0;
do {
//Prompt what country the order is for
System.out.println("What country is the order for? (press '0' to see the Net Total of order) ");
System.out.println("1: Europe\n2: U.S.");
holder = input.nextInt();
// 110 or 240 voltage
if (holder == 1) {
//How many boxes are ordered EUROPE
System.out.println("Input number of 240v boxes needed");
v240 = input.nextInt();
total = 2.40 * v240;
System.out.println("Order total: $" + total);
} else if (holder == 2) {
// How many boxes are ordered US
System.out.println("Input number of 110v boxes needed");
v110 = input.nextInt();
total = 2.40 * v110;
}
// Discount for U.S.
if (holder == 2) {
if (v110 >= 3)
discount = total * .05;
} else if (v110 >= 10) {
discount = total * .10;
}
if (discount > 0) {
System.out.println("Order total: $" + total);
System.out.println("Total with Discount: $" + (total - discount));
}
} while ((v240 != 0) || (v110 != 0));
}
}
In order to finish the loop i would use holder instead of v110 and v240 this way you dont need to enter a country and then an order amount.
The problem can be due to that if you first select US and enter a value this value is retained until you enter again US an another amount so your loop wonth end unless you select allways the same country and then select 0 as amount
To accumulate total you should do
total += 2.40*v240;
or
total=total+(2.40*v240);
This way the total amount will get increased on each loop
In order to format the output you can use this code fragment:
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(total));
I hope this may help you to familiarize with programming and Java.
Once you capture an input, your while condition can never be true, hence the infinite loop. Instead of
while ((v240 != 0) || (v110 != 0));
try
while (holder != 0);
Either that, or you will need to reset v240 and v110 to zero each time you repeat the loop.
Using printf is the simplest to achieve this.
System.out.printf("%.2f", total);
So for your case:
System.out.printf("Order total: %.2f", total);
You can also use DecimalFormat to show up to the digit you want to print.
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("Order total: $" + df.format(total));