this basic JAVA program should prompt the user, and print "Negative numbers are not allowed" until user enters a positive number. This must be handled by using while loop. how does it work ? This is my first post in stack overflow.
public static void main(String[] args)
{
System.out.print("Welcome to Box Price Calculator");
System.out.print(System.lineSeparator());
System.out.print(System.lineSeparator());
int boxVol = 20 ;
double price_each_box = 2.99;
System.out.print("Bottles :");
Scanner input = new Scanner(System.in);
int numberOfbottles = 1;
numberOfbottles = input.nextInt();
boolean valid = false;
while (input.nextInt() < 0){
System.out.println("Negative numbers are not allowed");
numberOfbottles = input.nextInt();
}
int box = (numberOfbottles / boxVol);
System.out.println("Box Needed : " + box);
double totPrice = (box * price_each_box);
System.out.println("Total Cost : $" + totPrice);
int leftOver = (numberOfbottles -(box * boxVol));
System.out.println("Unboxed :" + leftOver);
}
}
The problem here is that you are reading and compare again with input.nextInt() and not with numberOfbottles, inside the while condition. What you should do is to use a do...while and compare it with your variable numberOfbottles:
public static void main(String[] args)
{
System.out.print("Welcome to Box Price Calculator");
System.out.print(System.lineSeparator());
System.out.print(System.lineSeparator());
int boxVol = 20 ;
double price_each_box = 2.99;
java.util.Scanner input = new java.util.Scanner(System.in);
int numberOfbottles;
do
{
System.out.println("Bottles (Negative numbers are not allowed):");
numberOfbottles = input.nextInt();
}
while (numberOfbottles < 0);
int box = (numberOfbottles / boxVol);
System.out.println("Box Needed : " + box);
double totPrice = (box * price_each_box);
System.out.println("Total Cost : $" + totPrice);
int leftOver = (numberOfbottles -(box * boxVol));
System.out.println("Unboxed :" + leftOver);
}
I have some review questions for an upcoming test in my Java class, the one I am working on at the moment asks us to create a cafe menu with two arrays, one with menu items and the other with prices. We have to print the average of all the prices before asking the user which item(s) from the menu they want and then finally print the total of the items.
My code:
import java.util.Scanner;
public class cafeMenu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
double total = 0;
//Array for storing prices
double [] cafePrice = new double[5];
cafePrice[0]= 6.99;
cafePrice[1]= 5.99;
cafePrice[2]= 2.99;
cafePrice[3]= 1.50;
cafePrice[4]= 2.50;
//Menu item array
String [] cafeDrink = new String[5];
cafeDrink[0] = "Macchiato";
cafeDrink[1] = "Latte";
cafeDrink[2] = "Americano";
cafeDrink[3] = "Tea";
cafeDrink[4] = "Cappichino";
//Welcome user and gather their menu selection
System.out.println("Welcome to our cafe! Please enjoy!");
System.out.printf("The average pricing for our drinks is: %.2f \n", + cafeAvg( cafePrice));
System.out.println("Please enter a menu selection:\n"
+ "0. Macchiato -- $6.99\n"
+ "1. Latte -- $5.99\n"
+ "2. Americano -- $2.99\n"
+ "3. Tea -- $1.50\n"
+ "4. Cappichino -- $2.50");
choice = input.nextInt();
//Add up the total
for(int i = 0; i < cafePrice.length; i++ ) {
if(choice == cafePrice[i]) {
total += cafePrice[i];
}
}
System.out.println("Your total is: " + total);
}
//Method for average menu price
public static double cafeAvg(double[] array) {
double sum = 0;
double sum2 = 0;
for(int i = 0; i < array.length; i++) {
sum += array[i];
sum2 = sum /array.length;
}
return sum2;
}
}
I haven't set up a do while loop just yet to continue to ask the user for input because I've sort of gotten stuck with adding the prices together. I'd imagine I've made an error in my for loop, or possibly a logic error?
This is the result I keep getting, regardless of the choice made:
Welcome to our cafe! Please enjoy!
The average pricing for our drinks is: 3.99
Please enter a menu selection:
0. Macchiato -- $6.99
1. Latte -- $5.99
2. Americano -- $2.99
3. Tea -- $1.50
4. Cappichino -- $2.50
4
Your total is: 0.0
Any ideas would be greatly appreciated.
You are doing the following incorrectly,
if(choice == cafePrice[i]) {
total += cafePrice[i];
}
choice is an int while cafeprice[i] is a double ... moreover they represent different things. You actually want to do the following I think,
total += cafePrice[choice];
instead of the whole for loop.
This code works for me,
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int choice;
double total = 0;
//Array for storing prices
double [] cafePrice = new double[5];
cafePrice[0]= 6.99;
cafePrice[1]= 5.99;
cafePrice[2]= 2.99;
cafePrice[3]= 1.50;
cafePrice[4]= 2.50;
//Menu item array
String [] cafeDrink = new String[5];
cafeDrink[0] = "Macchiato";
cafeDrink[1] = "Latte";
cafeDrink[2] = "Americano";
cafeDrink[3] = "Tea";
cafeDrink[4] = "Cappichino";
//Welcome user and gather their menu selection
System.out.println("Welcome to our cafe! Please enjoy!");
System.out.printf("The average pricing for our drinks is: %.2f \n", + cafeAvg( cafePrice));
System.out.println("Please enter a menu selection:\n"
+ "0. Macchiato -- $6.99\n"
+ "1. Latte -- $5.99\n"
+ "2. Americano -- $2.99\n"
+ "3. Tea -- $1.50\n"
+ "4. Cappichino -- $2.50");
choice = input.nextInt();
//Add up the total
total += cafePrice[choice];
System.out.println("Your total is: " + total);
}
//Method for average menu price
public static double cafeAvg(double[] array) {
double sum = 0;
double sum2 = 0;
for(int i = 0; i < array.length; i++) {
sum += array[i];
sum2 = sum /array.length;
}
return sum2;
}
Hey new guy here need assistance in my problem! i need to print previous user input data from a loop the problem is that it prints the last data the user inputs. Please shed some light my mind is getting dark. I appreciate all of you answers. Thank you!
My program: (Sorry if it's disgusting af)
package activity2;
import java.util.Scanner;
public class Activity2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
for (x=0;x<a;x++){
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sum +=q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
for(int t=0; t<x; t++){
System.out.println(pnum[sum2]+"."+name[sum2]+"---------"+v);
}
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
}
One approach is to use a StringBuilder.
(direct quote below from link)
"StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations."
You can save data with StringBuilder, then print everything all at one time. This makes life a little easier too ;-)
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (x=0;x<a;x++) {
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sb.append(pnum[sum2]+"."+name[sum2]+"---------"+q + "\n");
sum +=q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
System.out.println(sb);
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
This will give you the output you're looking for.
The issue is you're not saving each entry. If you want to be able to print it back at the end you need to do this. I'm not exactly sure what you're trying to do, but this should at least give you an idea on what you need to do in order to be able to print out transaction details. Also you really need to name your variables a lot better.
import java.util.Scanner;
public class Activity2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] name = {"Milk","Juice","Energy drink","Water","Softdrink","Beer","Wine","Coffee"};
int[] pnum = {0,1,2,3,4,5,6,7};
double[] price = {300,100,220,120,200,350,400,130};
String[] list = {"Enter product #: ","Enter quantity: ","Sub-total: "};
double sum=0,q=0,v,s;
int sum2=0, w;
String z = "";
int x,c = 0;
System.out.println(" Product Information");
System.out.println("------------------------------------------");
System.out.println("Name Price");
System.out.println("------------------------------------------");
System.out.println(pnum[0]+"."+name[0]+" "+price[0]);
System.out.println(pnum[1]+"."+name[1]+" "+price[1]);
System.out.println(pnum[2]+"."+name[2]+" "+price[2]);
System.out.println(pnum[3]+"."+name[3]+" "+price[3]);
System.out.println(pnum[4]+"."+name[4]+" "+price[4]);
System.out.println(pnum[5]+"."+name[5]+" "+price[5]);
System.out.println(pnum[6]+"."+name[6]+" "+price[6]);
System.out.println(pnum[7]+"."+name[7]+" "+price[7]);
System.out.println("------------------------------------------");
do{
System.out.print("Enter number of products: ");
int a = sc.nextInt();
int[] productNum = new int[a];
String[] products = new String[a];
double[] prices = new double[a];
for (x=0;x<a;x++){
System.out.print(list[0]);
w = sc.nextInt();
sum2 =w;
System.out.print(list[1]);
s = sc.nextDouble();
q = s * price[w];
System.out.println(list[2]+q);
sum +=q;
productNum[x] = w;
products[x] = name[w];
prices[x] = q;
}
System.out.println("Total: " + sum);
System.out.print("Do you want another transaction?(y/n):");
z = sc.next();
x = a;
v = q;
System.out.println("Transaction Details");
for(int t=0; t<x; t++){
System.out.println(productNum[t]+"."+products[t]+"---------"+prices[t]);
}
System.out.println("TOTAL: " + sum);
System.out.print("Enter cash amount: ");
double i = sc.nextDouble();
if(sum>i){
System.out.println("Cash is insuffecient! Please try again:");
System.out.print("Enter cash amount: ");
i = sc.nextDouble();
}
double tc = i - sum;
System.out.print("Cash change"+tc);
}
while(z.equals("y"));
}
}
import java.util.*;
public class Averages{ //name class as public
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //initialized string using 'new'
String Course;
int knowledgemark;
int communicationmark;
int thinkingmark;
int applicationmark;
int average;
int finalexam;
int average2;
String answer;
int maxK;
int maxC;
int maxA;
int maxT;
int knowledgeweight;
int communicationweight;
int thinkingweight;
int applicationweight;
String Assignment;
String Test;
int average3;
int weight;
int weightaverage;
int average4= 0;
System.out.println("What class are you calculating for?");
Course = Scan.nextLine();
System.out.println("What's your knowledge mark for this course?");
knowledgemark = Scan.nextLine();
System.out.println("What's your application mark for this course?");
applicationmark = Scan.nextLine();
System.out.println("What's your thinking mark for this course?");
thinkingmark = Scan.nextLine();
System.out.println("What's your communication mark for this course?");
communicationmark = Scan.nextLine();
average = ((knowledgemark + communicationmark + applicationmark + thinkingmark)/4);
average = Scan.nextInt();
System.out.println("Your average for" + Course + "is" + average);
System.out.println("Do you want to calculate your exam with your final exam mark? (yes or no)");
answer = Scan.next();
if(answer.equals ("yes")){
System.out.println("What is your final exam mark?");
finalexam = scan.nextInt();
average2 = (((average * 70) + finalexam * 30) /100);
System.out.println("Your final average in this course is" + average2);
}
else{
System.out.println("You average for" + Course + "is" + average);
}
System.out.println("You can also calculate your marks with tests/assignments");
Test = Scan.nextLine();
System.out.println("What test/assignment are you calculating for?");
Test = Scan.nextLine();
System.out.println("What is the weighting for knowledge?");
knowledgeweight = Scan.nextLine();
System.out.println("What is your knowledge mark for the test/assignment?");
maxK = Scan.nextLine();
System.out.println("What is the weighting for communication?");
communicationweight = Scan.nextLine();
System.out.println("What is your communication mark for the test/assignment?");
maxC = Scan.nextLine();
System.out.println("What is the weighting for application?");
applicationweight = Scan.nextLine();
System.out.println("What is your application mark for the test/assignment?");
maxA = Scan.nextLine();
System.out.println("What is the weighting for knowledge?");
thinkingweight = Scan.nextLine();
System.out.println("What is your thinking mark for the test/assignment?");
maxT = Scan.nextLine();
average3 = (maxK * knowledgeweight + maxC * communicationweight + maxT * thinkingweight + maxA * applicationweight);
System.out.println("Your final average for this test/assignment is" + average3);
System.out.println("What is the weight of the test/assignment (10, 30, 50)?");
weightaverage = Scan.nextInt;
weightaverage = (average3 * weightaverage);
System.out.println("Your assignment/test weighted is" + weightaverage);
int length;
Scanner scan = new Scanner(System.in);
System.out.println("How many classes do you have?");
length = scan.nextInt();
int[] firstArray = new int[length];
for(int i=0; i<length; i++){
System.out.println("What is your course mark for each class in order" + (1 + i) + "?");
firstArray[i] = scan.nextInt[];
}
}
}
Here is my code. The error is near the bottom of the page. Thanks ahead of time!
Please hep me fix this as I do not know what to do
It is my only error left to compile.
Thanks and greatly appreciated!
Edit: Formatted to show code in one snippet.
You are missing () in your call to nextInt() at
weightaverage = Scan.nextInt;
change it to something like
weightaverage = Scan.nextInt();
and
firstArray[i] = scan.nextInt[];
should be
firstArray[i] = scan.nextInt();
And, you aren't consistent with your Scanner name.
Scanner sc = new Scanner(System.in);
needs to be
Scanner Scan = new Scanner(System.in);
if you're going to call Scan.nextInt(). Also, you are calling nextLine() (which returns a String) and assigning the result to int variables.
Here's the code corrected with suggestions made by Elliott Frisch.
To reiterate:
You declared Scanner with the variable name sc, but used Scan.nextLine() in the remainder of the code. The correction is sc.nextLine().
sc.nextLine() cannot be converted to String. It returns an integer so for example, int knowledgemark = sc.nextInt(); is correct.
Some code was using sc.nextInt; or sc.nextInt[]; which should be corrected to sc.nextInt();.
import java.util.*;
public class Averages { //name class as public
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //initialized string using 'new'
String Course;
int knowledgemark;
int communicationmark;
int thinkingmark;
int applicationmark;
int average;
int finalexam;
int average2;
String answer;
int maxK;
int maxC;
int maxA;
int maxT;
int knowledgeweight;
int communicationweight;
int thinkingweight;
int applicationweight;
String Assignment;
String Test;
int average3;
int weight;
int weightaverage;
int average4 = 0;
System.out.println("What class are you calculating for?");
Course = sc.nextLine();
System.out.println("What's your knowledge mark for this course?");
knowledgemark = sc.nextInt();
System.out.println("What's your application mark for this course?");
applicationmark = sc.nextInt();
System.out.println("What's your thinking mark for this course?");
thinkingmark = sc.nextInt();
System.out.println("What's your communication mark for this course?");
communicationmark = sc.nextInt();
average = ((knowledgemark + communicationmark + applicationmark + thinkingmark) / 4);
average = sc.nextInt();
System.out.println("Your average for" + Course + "is" + average);
System.out.println("Do you want to calculate your exam with your final exam mark? (yes or no)");
answer = sc.next();
if (answer.equals("yes")) {
System.out.println("What is your final exam mark?");
finalexam = sc.nextInt();
average2 = (((average * 70) + finalexam * 30) / 100);
System.out.println("Your final average in this course is" + average2);
} else {
System.out.println("You average for" + Course + "is" + average);
}
System.out.println("You can also calculate your marks with tests/assignments");
Test = sc.nextLine();
System.out.println("What test/assignment are you calculating for?");
Test = sc.nextLine();
System.out.println("What is the weighting for knowledge?");
knowledgeweight = sc.nextInt();
System.out.println("What is your knowledge mark for the test/assignment?");
maxK = sc.nextInt();
System.out.println("What is the weighting for communication?");
communicationweight = sc.nextInt();
System.out.println("What is your communication mark for the test/assignment?");
maxC = sc.nextInt();
System.out.println("What is the weighting for application?");
applicationweight = sc.nextInt();
System.out.println("What is your application mark for the test/assignment?");
maxA = sc.nextInt();
System.out.println("What is the weighting for knowledge?");
thinkingweight = sc.nextInt();
System.out.println("What is your thinking mark for the test/assignment?");
maxT = sc.nextInt();
average3 = (maxK * knowledgeweight + maxC * communicationweight + maxT * thinkingweight + maxA * applicationweight);
System.out.println("Your final average for this test/assignment is" + average3);
System.out.println("What is the weight of the test/assignment (10, 30, 50)?");
weightaverage = sc.nextInt();
weightaverage = (average3 * weightaverage);
System.out.println("Your assignment/test weighted is" + weightaverage);
int length;
Scanner scan = new Scanner(System.in);
System.out.println("How many classes do you have?");
length = scan.nextInt();
int[] firstArray = new int[length];
for (int i = 0; i < length; i++) {
System.out.println("What is your course mark for each class in order" + (1 + i) + "?");
firstArray[i] = scan.nextInt();
}
}
}
I have just started learning Java in the last week or so and I'm creating a program that acts as a sales calculator that calculates commission.
My code is as follows:
import java.util.Scanner;
public class Application {
int itemOne;
int itemTwo;
int itemThree;
int itemFour;
final double baseCommission = 200;
final double itemOnePrice = 239.99;
final double itemTwoPrice = 129.75;
final double itemThreePrice = 99.95;
final double itemFourPrice = 350.89;
final double commissionPercentage = 0.09;
boolean startLoop = false;
public void start(){
while (startLoop = false);
{
//Welcome message
System.out.println("Welcome to Devon's Sales Calculator!");
//Defining new scanner
Scanner user_input = new Scanner(System.in);
//Getting user input for salesperson name along with number of items sold as well as assigning them to a variable
String salesman_name;
System.out.print("Insert salesperson name:\t");
salesman_name = user_input.next();
System.out.print("Enter number of first item sold:\t");
int first_item = user_input.nextInt();
System.out.print("Enter number of second item sold:\t");
int second_item = user_input.nextInt();
System.out.print("Enter number of third item sold:\t");
int third_item = user_input.nextInt();
System.out.print("Enter number of fourth item sold:\t");
int fourth_item = user_input.nextInt();
//Printing out the name of the salesmen, followed by the total price of items sold
System.out.println("Sales Person\t" + salesman_name);
System.out.println("Total price of first item sold\t" + first_item * itemOnePrice);
System.out.println("Total price of second item sold\t" + second_item * itemTwoPrice);
System.out.println("Total price of third item sold\t" + third_item * itemThreePrice);
System.out.println("Total price of fourth item sold\t" + fourth_item * itemFourPrice);
//Calculating total of all items sold
double finalPrice = first_item * itemOnePrice + second_item * itemTwoPrice + third_item * itemThreePrice + fourth_item * itemFourPrice;
//Calculating commission # 0,9%
System.out.println("Total commission earned\t" + finalPrice * commissionPercentage);
//Decision whether or not to restart the while loop
String decision;
System.out.println("Would you like to check another salesperson?");
decision = user_input.next();
if(decision == "yes"){
startLoop = false;
}
else if(decision == "no"){
startLoop = true;
}
}
}
}
Whenever I execute my while loop, it doesn't restart to choose another salesman. I'm probably doing something horribly wrong and my code formatting is probably horrible. Any help would be appreciated.
Get rid of the = false and the semicolon. So not:
while (startLoop = false);
{
System.out.println("foo");
}
which is equivalent to
while (startLoop = false) {
// do nothing
}
{
System.out.println("foo");
}
Instead do,
while (!startLoop) {
// do something here
}