I've never made a loop before and have to for a project.
Here is what I have:
import java.util.Scanner;
public class Population
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in);
int dailyPopInc=-1;
System.out.print("What is the starting number of organisms? ");
int population = kb.nextInt();
if (population>1){System.out.print("What is the daily population increase as a percentage? ");
dailyPopInc= kb.nextInt();}
else System.out.println("Error");
int daysMultiplied=0;
if (dailyPopInc>=0){System.out.print("How many days will they multiply? ");
daysMultiplied= kb.nextInt();}
int k=0;
for (k=1;k<daysMultiplied;k++){
population= population + population*(dailyPopInc/100);
System.out.println("The the amount of population on day "+k+" is " + population);
}
}
}
I keep getting things like
"The amount of population on day 1 is 89" and it only changes the day value.
The population never changes. Can somebody please show me my mistakes?
Modify these lines:
double population = kb.nextInt();
population= population + population*(dailyPopInc/100.0);
It is because dailyPopInc/100 as an integer is always 0.
Related
Write the complete java program called Temperature that includes a for loop structure, prompting the user to enter 5 temperature values. The program should add up each temperature entered within the loop and this is stored in a variable called total. Using a system statement, output the total temperature value and the average temperature value. Use the sample output below as a guide:
The total temperature =
The average temperature =
My answer is the statement below but im still getting errors:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner temp = new Scanner (System.in);
double total = 0;
for(int=1;int<=5;int++);
{
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total = temperature;
}
System.out.println("The total temperature =" +total);
System.out.println("The average temperature=" +(double)(total/5));
}
}
The OP does not state what errors you are getting exactly, but I can guess some of them are from:
for(int=1;int<=5;int++);
You cannot use int like that. It is a type and should be used like the following:
for(int itr = 1; itr <= 5; itr++) { ...
Also, the semi-colon on your for loop doesn't need to be there.
for(int i=1;i<=5;i++) {
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total += temperature;
}
once the user presses 2 times y and the next time n when they enter n how to display the total price of item1 and item2
import java.util.Scanner;
import javax.swing.JOptionPane;
public class ITPL_Coursework {
public static void main(String[] args) {
String itemStr ;
String quantityStr;
final double tax=0.03;
double total = 0;
int price;
char choice;
// System.out.print("\nEnter number of the hardware component you want: ");
System.out.println("\tHari's Hardware Company ");
System.out.println("\t-----------------------");
System.out.println("\nAvailable hardware components and its price are listed below: \n1:HYPERX FURY RAM \n2:Graphics Card");
do{
itemStr=JOptionPane.showInputDialog("Enter number of the hardware component you want: ");
int item=Integer.parseInt(itemStr);
quantityStr=JOptionPane.showInputDialog("Enter the quanity of the hardware component you want:");
int quantity=Integer.parseInt(quantityStr);
if(item==1){
price=1500;
total=(tax*(price*quantity));
System.out.println("You choose to buy HYPERX FURY RAM for: " +total);
}
if(item==2){
price=1000;
total=(tax*(price*quantity));
System.out.println("You choose to buy Graphics Card for: " +total);
}
System.out.print("Do you want to continue y/n?:");
Scanner console = new Scanner(System.in);
choice=console.next().charAt(0);
}
while(choice=='y');
System.out.println(""+total);
}
}
total=(tax*(price*quantity));
This only assigns total to be the current cost. If you want to sum all costs, then you need to use +=:
total += (tax*(price*quantity));
Good day! I am trying to make a program that will ask the user to input the total number of the items. After the input of the total items, the program should ask the price of each item, based on the input. After the input of the prices, the program should compute the total price and ask for the cash. If the cash is not sufficient to pay the items, allow the user to re-enter cash until he/she inputted enough to pay the bill. Lastly, it will print the change of the user.
My problem is, how to I compute the price of each item. I think I need an array to save each prices and compute them afterwards. Here is my program, I know its a mess, sorry im still a beginner. Hoping for a solution. Thank you so much!!
public class Store {
public static void main(String[] args) {
Scanner v = new Scanner (System.in);
int totalitems;
int change;
int cash;
double price[];
double totalprice;
System.out.print("Enter Total Number of Items: ");
totalitems = v.nextInt();
for(int loop=1; loop<=totalitems; loop++) {
System.out.print("Enter the price of each item: ");
price[totalitems] = v.nextInt();
}
//i need a solution here for array
System.out.print("Enter the your cash: ");
cash = v.nextInt();
if(cash < totalprice) {
System.out.print("Please input a sufficient amount: ");
cash = v.nextInt();
}else {
change = cash - totalprice;
}
System.out.print("Thank you! Your change is: " + change);
}
}
You can iterate over the price array, either in the old-fashioned way:
for(int loop=0; loop < totalitems; loop++) {
totalPrice = totalPrice + price[loop];
}
or, in the new way:
for (double itemPrice : price) {
totalPrice = totalPrice + itemPrice;
}
But you're forgetting something else as well: the price[] array isn't initialized. As soon as the totalItems is known, you must do
price[] = new double[totalItems];
Otherwise Java wouldn't know how much memory to reserve for the array.
I made a program to calculate total price based on user's input. It is working fine, but i would like to know how to cut the code but to have the same output.
Especially on IF ELSE statement, I would like to know how not to repeat myself in those blocks. Is there any other way I can write ouputs after IF ELSE blocks, or they have to be individually inside of those blocks? Thanks.
Here is the code
import java.util.Scanner;
import java.text.*;
public class GasCalc
{
public static void main(String[] args)`enter code here`
{
double gasPrice,carGallons,fullTank,totalPrice;
Scanner input=new Scanner(System.in);
System.out.print("Do you want to calculate full tank (y/n) ");
String askMe=input.next();
if
(askMe.equalsIgnoreCase("y"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
System.out.print("How many gallons does your vehicle accept ? ");
fullTank=input.nextDouble();
totalPrice=gasPrice*fullTank;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
}
else
if(askMe.equalsIgnoreCase("n"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("How many gallons do you need ? ");
carGallons=input.nextDouble();
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
totalPrice=gasPrice*carGallons;
System.out.println("You will pay "+num.format(totalPrice)+" for "+carGallons+" gallons of gas");
}
}
}
If I understand your question correctly - you don't want to repeat the same code in the 'if' and the 'else' parts of an if statement.
The way you would do this is to the same as anywhere else: extract the common code as a function/method which is called from both places.
You can move the last two statements outside, that way your calculation and printing can be done outside the if-else block.
You can rename fullTank and carGallons to gallons, so both variables have the same name, that way the last two statements can be used outside if-else.
totalPrice=gasPrice*gallons;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
Use a method and factorize the local variable num, used in both if and else :
public class GasCalc {
private static double readDouble(Scanner in, String msg) {
System.out.print(msg);
return in.nextDouble();
}
private static String readString(Scanner in, String msg) {
System.out.print(msg);
return in.next();
}
public static void main(String[] args) {
double gasPrice, carGallons, fullTank, totalPrice;
Scanner input = new Scanner(System.in);
String askMe = readString(input,"Do you want to calculate full tank (y/n) ");
DecimalFormat num = new DecimalFormat("$,###.00");
if (askMe.equalsIgnoreCase("y")) {
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
fullTank = readDouble(input,"How many gallons does your vehicle accept ? ");
totalPrice = gasPrice * fullTank;
System.out.println("You will pay " + num.format(totalPrice) + " for the full tank of gas");
} else if (askMe.equalsIgnoreCase("n")) {
carGallons = readDouble(input,"How many gallons do you need ? ");
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
totalPrice = gasPrice * carGallons;
System.out.println("You will pay " + num.format(totalPrice) + " for " + carGallons + " gallons of gas");
}
}
}
You could actually factorize even more but it would make little sense to create another method for such a specific treatment. If you are using JDK 8 and understand the lambda expressions, go for it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);