issue with java while statement? - java

My code compiles correctly. When I run my program the output asks me to enter weight of package. If I enter a negative number the program asks me to enter weight again, but won't stop to let me enter another number.
I think the problem is in the "while" statement but I'm not sure.
Any help would be appreciated.
import java.util.Scanner;
public class dcrawford_Shipping
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int weight, distance, distancex;
double rate, price;
rate = 0.00;
System.out.print("Please enter package weight: ");
weight = input.nextInt();
while (weight <= 0 || weight >= 61)
{
System.out.print("Please enter package weight: ");
}
if (weight <= 10 && weight >= 1 )
{
rate = 5.01;
}
else if ( weight <= 20 && weight >= 11 )
{
rate = 7.02;
}
else if ( weight <= 30 && weight >= 21 )
{
rate = 9.03;
}
else if ( weight <= 40 && weight >= 31 )
{
rate = 11.04;
}
else if ( weight <= 60 && weight >= 41)
{
rate = 15.00;
}
System.out.print("Please enter distance: ");
distance = input.nextInt();
while ( distance <= 0 )
{
System.out.print("Please enter distance: ");
}
distancex = ( distance / 100 ) + 1;
price = ( distancex * rate );
System.out.printf("Your total shipping cost for %d miles is $%.2f\n", distance, price);
}
}

You need to ask the user to enter the weight again inside of the while loop.
while (weight <= 0 || weight >= 61) {
System.out.print("Please enter package weight: ");
weight = input.nextInt();
}
You could also use a do-while loop:
do {
System.out.print("Please enter package weight: ");
weight = input.nextInt();
} while (weight <= 0 || weight >= 61);
If you use the do-while loop, you can remove the first time you ask and the while loop. It's a slightly more compact way of doing it.

Related

Java BMI program

The first part of the code is working, the program takes inputs as height and weight as displays an output message. When I press n I can go to the second part and take inputs for height in inches and the weight in pounds. As soon as I take them the program outputs the resulting bmi is: Nan. and the variable bmi might not have been initialized. i want to convert the height and weight from inches and pounds to meters and then show the resulting bmi This is my code:
package uly14th;
import java.util.Scanner;
public class BmiCalculator {
private static float BMI2;
public static void main(String[] args) {
char Y;
char y;
char Q;
char n;
char N;
float heightInMeters, weightInKilograms, BMI;
float heightInInches, weightInpounds;
float heightInMeters2 = 0, weightInKilograms2 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please state whether you are going to use kilograms & meters or, inches & pounds");
System.out.println("If you want to use the former please press Y or if you want to use the latter please press N");
Q = input.next().charAt(0);
if(Q == 'y' || Q == 'Y' ) {
System.out.println("Please enter the height in meters: ");
heightInMeters = input.nextFloat();
System.out.println(" and weight in kilograms: ");
weightInKilograms = input.nextFloat();
BMI = weightInKilograms / (heightInMeters * heightInMeters);
System.out.println("The resulting BMI of the person is: " +BMI);
if (BMI < 18.5){
System.out.println("The personis underweight");
}
else if ((BMI<=25.0) && (BMI >= 18.5)){
System.out.println("The person is normal");
}
else if ((BMI >= 25.0) && (BMI <=30.0 )){
System.out.println("The personis obese");
}
else if(BMI>=30.0) {
System.out.println("The person is obese and should exercise");
}
}
if ((Q == 'n') || (Q == 'N')){
System.out.println("Please enter the height in inches: ");
heightInInches = input.nextFloat();
System.out.println("Please enter the weight in pounds: ");
weightInpounds = input.nextFloat();
heightInInches = 0.0254f * heightInMeters2;
weightInpounds = 0.453592f * weightInKilograms2;
BMI = weightInKilograms / (heightInMeters * heightInMeters);
System.out.println("The resulting BMI of the person is: " +BMI);
if (BMI < 18.5){
System.out.println("The personis underweight");
}
else if ((BMI<=25.0) && (BMI >= 18.5)){
System.out.println("The person is normal");
}
else if ((BMI >= 25.0) && (BMI <=30.0 )){
System.out.println("The personis obese");
}
else if(BMI>=30.0) {
System.out.println("The person is obese and should exercise");
}
}
else {
System.out.println("Please make sure you run the program again and then only use the characters n,N,y,Y. ");
}
}
}
This is the error message: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - variable BMI might not have been initialized
at uly14th.BmiCalculator.main(BmiCalculator.java:82)
At the row (line 82)
BMI = weightInKilograms / (heightInMeters * heightInMeters);
you use the variables weightInKilograms and heightInMeters which has never been initialized, hence your error.
I suspect you want to do the conversion to meters and kilograms from inches and pounds before calculating the BMI. You can do this by simply putting the following lines before the BMI calculation
heightInMeters = 0.0254f * heightInInches;
weightInKilograms = 0.453592f * weightInPounds;
BMI = weightInKilograms / (heightInMeters * heightInMeters); //Now you can calculate the BMI using your variables since they have been assigned a value and is therefore initialized
heightInMeters = 0.0254f * heightInInches ;
weightInKilograms = 0.453592f * weightInpounds ;
BMI = weightInKilograms / (heightInMeters * heightInMeters);
should do the trick (... in case the constants are correct)

How do I make a condition that could combine said plans in the program, and add their prices?

I am new to Java.
How do I make a condition that could possibly combine the said "plans" in the program and add their prices? For now the program is only set for one plan and price. Which can only output one plan, and price.
Like for example if I input:
Enter number of talk minutes: 125
Enter number of text messages sent: 225
Enter number of gigabytes used: 1.3
The outcome should be like
Recommended Cellular Plans: Plan B and Plan E
Total Bill: $134.00
import java.text.DecimalFormat;
import java.util.Scanner;
public class HorizonPhones {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of talk minutes: ");
int minutes = scanner.nextInt();
System.out.print("Enter amount of text messages sent: ");
int texts = scanner.nextInt();
System.out.print("Enter amount of gigabytes used: ");
double gigaBytes = scanner.nextDouble();
double planA = 49.00;
double planB = 55.00;
double planC = 61.00;
double planD = 70.00;
double planE = 79.00;
double planF = 87.00;
if (minutes <= 500 && texts == 0 && gigaBytes == 0 ) {
System.out.println("Recommended Cellular Plans: Plan A");
System.out.println("Total Bill: " + planA);
return;
}
if (minutes < 500 && texts > 1 && gigaBytes == 0) {
System.out.println("Recommended Cellular Plans: Plan B");
System.out.println("Total Bill: " + planB);
return;
}
if (minutes > 500 && texts <= 100 && gigaBytes == 0) {
System.out.println("Recommended Cellular Plans: Plan C");
System.out.println("Total Bill: " + planC);
return;
}
if (minutes > 500 && texts >= 100 && gigaBytes == 0) {
System.out.println("Recommended Cellular Plans: Plan D");
System.out.println("Total bill: " + planD);
return;
}
if (minutes > 500 && texts >= 1 && gigaBytes < 2) {
System.out.println("Recommended Cellular Plans: Plan E");
System.out.println("Total bill: " + planE);
return;
}
if (minutes > 500 && texts > 1 && gigaBytes > 2) {
System.out.println("Recommended Cellular Plans: Plan F");
System.out.println("Total bill: " + planF);
return;
}
}
}
Before you if(){} blocks start declare two things one String[] (for storing plan's name) and another int sum=0; variable for storing total sum. And remove return from each if(){} block. Then in each block just do this.
String[] plansName = new String[];
int sum = 0;
if (minutes <= 500 && texts == 0 && gigaBytes == 0 ) {
plansName.push("planA");
sum += planA;
}
...
Similarly do for all if(){} blocks and at the end print plansName and sum values.

Java Based on this input, the program will display the number of integers in less than 50

for the task i need to Write a Java application that accepts 30 integer numbers from the user. The input should be in the range of 1-200. Error message needs to be displayed if user entered input which is not in this range. Based on this input, the program will display the number of integers entered in the following categories:
 Less than 50
 Between 50-100 (inclusive of 50 and 100)
Sample output :
Enter number 4: 211
Input error..Pls enter number between 1 to 200 only
Enter number 4: 20
..
..
Enter number 30: 90
Less than 50: 12
Between 50-100 (inclusive of 50 and 100): 8
Between 101-150 (inclusive of 101 and 150): 5
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
// a.Declare an array to hold 5 Integer values
int list[] = new int[5];
int i = 0;
System.out.print("\n\tInput numbers from 1 to 200: \n");
while (i < 5) {
// b.Fill the array with intgers from the keyboard(range: 1 to 200).
System.out.print("Enter Integer" + (i + 1) + ":");
int value = kbin.nextInt();
if (value >= 1 && value <= 200) {
list[i] = value;
i++;
} else {
System.out.println("!! Error! Please Enter Value between 1 and 200 !!");
}
}
}
}
Here is an example using Java Streams. Here we simply read all the values first, then filter out each category later. Performance wise, it's better to just use a counter for each category if you don't care about the actual numbers being counted though.
public class Test {
public static void main(String[] args) {
int counter = 0;
Scanner scanner = new Scanner(System.in);
List<Integer> values = new ArrayList<>();
while (counter < 5) {
System.out.print("Enter integer (" + (counter + 1) + "): ");
int value = scanner.nextInt();
if (value >= 1 && value <= 200) {
counter++;
values.add(value);
} else {
System.out.println("Please enter a value between 1 and 200");
}
}
System.out.println("Between 1-50 : " + values.stream().filter(val -> val < 50).count());
System.out.println("Between 50-100 : " + values.stream().filter(val -> val >= 50 && val <= 100).count());
System.out.println("Between 101-150: " + values.stream().filter(val -> val > 100 && val <= 150).count());
System.out.println("Between 151-200: " + values.stream().filter(val -> val > 150 && val <= 200).count());
}
Output example:
Enter integer (1): 5
Enter integer (2): 55
Enter integer (3): 125
Enter integer (4): 175
Enter integer (5): -2
Please enter a value between 1 and 200
Enter integer (5): 201
Please enter a value between 1 and 200
Enter integer (5): 199
Between 1-50 : 1
Between 50-100 : 1
Between 101-150: 1
Between 151-200: 2
It is a very simple problem here #Dilip. Just introduce a flag variable which would mark if an input is wrong. If it is, then just accept the value again. Else proceed.
Following is the code snippet for the input part also considering the wrong and right input boundaries.
System.out.print("\n\tInput numbers from 1 to 200: \n");
for(i = 0; i < 5; i++) {
flag = 0;
while(flag == 0) {
list[i] = kbin.nextInt();
if(!(list[i] < 1 || list[i] > 200)){
flag = 1;
}
else {
System.out.println("INVALID INPUT!!! Enter a valid number.");
}
}
}
I have gone through the problem statement which you have told about in the comments section and have coded the program which would serve the purpose. I have also attached the output for confirmation and reference. Hope this helps.
CODE:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
// a.Declare an array to hold 5 Integer values
int list[] = new int[5];
int category1[] = new int[5], k1 = 0;
int category2[] = new int[5], k2 = 0;
int category3[] = new int[5], k3 = 0;
int i, flag;
System.out.print("\n\tInput numbers from 1 to 200: \n");
for(i = 0; i < 5; i++) {
flag = 0;
while(flag == 0) {
System.out.print("Enter the input number " + (i+1) + ": ");
list[i] = kbin.nextInt();
if(!(list[i] < 1 || list[i] > 200)){
flag = 1;
}
else {
System.out.println("INVALID INPUT!!! Enter a valid number.");
}
}
}
for(i = 0; i < 5; i++) {
if(list[i] < 50)
category1[k1++] = list[i];
else if(list[i] < 101)
category2[k2++] = list[i];
else
category3[k3++] = list[i];
}
System.out.print("Category 1(1 TO 49): ");System.out.println(k1);
System.out.print("Category 2(50 TO 100): ");
System.out.println(k2);
System.out.print("Category 3(greater than 100): ");
System.out.println(k3);
System.out.print("Category 4(151 to 200): ");
System.out.println(k4);
}
}
OUTPUT:
Input numbers from 1 to 200:
Enter the input number 1: 2
Enter the input number 2: 3
Enter the input number 3: 50
Enter the input number 4: 56
Enter the input number 5: 159
Category 1(1 TO 49): 2
Category 2(50 TO 100): 2
Category 3(101 to 150): 0
Category 4(151 to 200): 1

Using a return value from a method in another method

I'm trying to use the return value "average" in calcAverage method into the determineGrade method to get out a char value (A B C D F).
However, it repeats the loop when I code this way. Is there a way to just get the return value from the calcAverage and not have to execute the loop again and ask the same test scores?
package Chapter5;
import java.util.Scanner;
public class TestAverageAndGradewithLoop {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("How many tests?: ");
int test = input.nextInt();
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
System.out.print("Letter grade is: " + determineGrade(mark) );
}
public static int calcAvergage(int test){
Scanner input = new Scanner (System.in);
int total = 0;
int x;
for (x = 1; x <= test; x++)
{
System.out.print("What is the score for test " + x + " : ");
int scores = input.nextInt();
total = total + scores;
}
int average = total/(x-1); //have to do -1 because the final increment value of x is stored as x+1
return average;
}
public static char determineGrade(int average)
{
char mark = 0;
if (average >= 90 && average <= 100)
{
mark = 'A';
}
else if (average >= 80 && average <= 89)
{
mark = 'B';
}
else if (average >= 70 && average <= 79)
{
mark = 'C';
}
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
return mark;
}
}
Instead of this:
System.out.print("Average test score is: " + calcAvergage(test) );
int mark = calcAvergage(test);
Do this
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark );
There is no need to call the function twice when you are playing with the return value. Assign it to a variable and then use it.
Like this?
int mark = calcAvergage(test);
System.out.print("Average test score is: " + mark);
From my understanding you do not want to input a number then press enter then enter another number then press enter and so on...
If you say you have 3 test cases in console just type 3 space separated numbers like 10 12 3.
Your question is confusing and your code has logical errors, im sorry. You have if statements using the same logic.(example below) I would say learn up more on programming logic and you will answer your own question
else if (average >= 60 && average <= 69)
{
mark = 'D';
}
else if (average <= 60)
{
mark = 'F';
}
Thx to Avinash Raj for the pointer. I understand now.
the result of the calcAverage is stored in the variable mark, then I can use the int value from the result to both display what the score is as well as display and execute the determineGrade method.

I need help understanding the programming challenge called Shipping Charges

The question says The Fast Freight Shipping Company charges the following rates:
Weight of Package Rate per 500 Miles Shipped
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80
The shipping charge per 500 miles are not prorated. For example, if a 2-pound package is shipped 550 miles, the charges would be $2.20. Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
My problem is that I keep receiving two different answers everytime I put in a weight and distance. For example when I enter the weight as 2 pounds and the distance as 500 miles I get the answers $0.0 and $3.8 which are both incorrect answers. It looks like some weights that I enter are correct answers and others I enter give me incorrect answers. Heres my program:
//import java utilities for scanner class
import java.util.Scanner;
public class ShippingCharge
{
public static void main (String[] args)
{
//Declare and initialize variable to hold the entered weight.
int weight = 0;
//Declare and initialize variable to hold the entered distance.
double distance = 0.0;
//This variable will hold the calculated rate.
double rate;
//This will decide if the shipping charge will advance up one level.
int distanceMultiplier = (int)distance / 500;
//This will hold the increments of the shipping charge.
int distanceRemainder;
//Create a Scanner object for the input.
Scanner input = new Scanner(System.in);
//Get the weight of the package.
System.out.println("What is the weight of the package (in pounds)?");
weight = input.nextInt();
//Get the shipping distance of the package.
System.out.println("What is the shipping distance (in miles)?");
distance = input.nextDouble();
distanceRemainder = (int)distance % 500;
if (distanceRemainder == 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.70));
}
else
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.80));
}
if (distanceRemainder != 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.70);
}
else
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.80);
}
//end program
System.exit(0);
}//end main
}//end class
This will work for you
public static void main(String[] args) {
int weight = 0;
double distance = 0.0 , distanceExtra ;
Scanner in = new Scanner(System.in);
System.out.println("Weight ? ");
weight = in.nextInt();
System.out.println("Distance ? ");
distance = in.nextDouble();
distanceExtra = distance / 500;
distanceExtra = Math.ceil(distanceExtra);
if (weight <= 2) {
System.out.printf("charge is :" , (distanceExtra * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.printf("charge is :" , (distanceExtra * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.printf("charge is :" , (distanceExtra * 3.70));
}
else if (weight > 10)
{
System.out.printf("charge is :" , (distanceExtra * 4.80));
}
}
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
int weight = 0;
double distance = 0.0 ;
Scanner keyboard =new Scanner(System.in);
System.out.println("Enter the Distance");
distance = keyboard.nextDouble();
System.out.println("Enter the Weight");
weight = keyboard.nextInt();
if (weight <= 2) {
System.out.println("charge is : " + "$"+1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("charge is : " + "$"+2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("charge is : " + "$"+3.70);
}
else if (weight > 10)
{
System.out.println("charge is :" + "$"+4.80);
}
}
}

Categories

Resources