I need to create a program that uses while to find the volume of a cylinder. I need the while loop to break if the user inputs a negative value for the height. My code looks like this:
double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
final double PI=3.14159;
boolean NotNegative=true;
while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
System.out.print("Enter height (Use negative to exit): "); // has the user input the height
h=Double.parseDouble(br.readLine());
sentinel=h; // save sentinel as the inputted height
while(sentinel>0){
System.out.print("Enter radius: "); // have the user input the radius
r=Double.parseDouble(br.readLine());
v=PI*(r*r)*h; // find the volume
System.out.println("The volume is " + v); // print out the volume
count++; // increase the count each time this runs
NotNegative=true;
sentinel=-1;
}
}
Any help?
You can throw an Exception which you catch and ignore. This is bad idea as
if and/or break is more efficient and simpler.
it's slow
it's confusing.
However, since you are using a while loop, which is like using an if & break, you can do the following.
NotNegative = h >= 0;
Add the following code inside the while(NotNegative){, after reading the input.
NotNegative = h >= 0;
Related
The question I am working on is:
Write a program that:
asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).
Sample program behavior / output:
How many exams scores do you have to enter? 5
Enter score #1: 95.0
Enter score #2: 92.0
Enter score #3: 68.0
Enter score #4: 72.0
Enter score #5: 70.0
The average score is: 79.4
There are 2 scores larger than the average.
This is my code:
import java.util.Scanner;
public class testee {
public static void main(String[] args) {
int examnum = -1;
Scanner scan = new Scanner (System.in);
while (examnum<0) {
System.out.println("How many exam scores do you have to enter?");
examnum = scan.nextInt( );
}
for (int i=1; i<=examnum; i++) {
System.out.println("Enter score #" + i + ": ");
for (int a=1; a<=i; a++) {
a = scan.nextInt();
}
}
}
}
What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.
First prompt looks good however there is one small problem.
Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?
It's always nice to inform the User of any invalid entry.
To place items into an Array you need to declare that array and initialize it to the proper size:
int[] scoresArray = new int[examnum];
Think about this, where do you think this line of code should be placed?
Hint: You need to ensure that the required array size is already properly established.
Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?
Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).
If you want to add an element to your array, where do you think would be a great place in your code to do that?
Hint: int score = scan.nextInt(); scoresArray[i] = score;.
Things to consider:
When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?
Yes, you can nest while loops within a for loop and visa-versa.
I'm having troubles figuring out how to increment a variable through an if statement, and allow it to be registered if called upon in a different if statement. I'm currently working on an assignment that mimics a menu for inputs. As shown, the user inputs a specific command, and on A, B, or C, they enter 3 scores/values. A separate input could be F, and on this input, it's supposed to show how many failures for each company, A, B, C has.
System.out.print("\nPlease enter a command:"); //Starts command prompt
String menuPrompt = scanner.next(); //Takes next input and uses one of the following if statements
if (menuPrompt.equals("a")) {
double aNum1;
double aNum2; //initializes a score inputs
double aNum3;
System.out.print("\nEnter number 1:");
aNum1 = scanner.nextDouble();
System.out.print("\nEnter number 2:");
aNum2 = scanner.nextDouble(); //asking for inputs of test values of company a
System.out.print("\nEnter number 3:");
aNum3 = scanner.nextDouble();
if(aNum1 < -6.0 || aNum1 > 12.3) {
aFailure = aFailure + 1;
}
if(aNum2 < -6.0 || aNum2 > 12.3) {
aFailure = aFailure + 1; //checks to see if inputted value is a failure, if so, failure ticks up 1.
}
if(aNum3 < -6.0 || aNum3 > 12.3) {
aFailure = aFailure + 1;
}
There are two other similar lines of code alike to this one just for "b" and "c". I initialized aFailure, bFailure, and cFailure at the top of the class and set their values to 0. After the if statements for the a, b, c prompts, I have this:
} else if (menuPrompt.equals("f")) {
System.out.print("\nAzuview Failures: " + aFailure);
System.out.print("\nBublon Failures: " + bFailure); //Lists total failures for each company
System.out.print("\nCryztal Failures: " + cFailure);
I'm not sure exactly how these variables are supposed to be defined, or if my formatting is even correct, help?
When you initialized a variable in a loop it is reinitialized every time the loop run again. When you initialized it outside of the loop it stays the same variable even in the loop. The concept behind a for loop is base on that.
In this example, the count is going to be incremented in every update of the while loop
So the count is going to be set to 0 and goes up by 1 until it reaches 9 when it will exit the loop
var count = 0;
while(count <10){
count++;
}
but in this one every time is going to loop in it. It reinitialized your variable count to 0 and increment it to 1. So every loop a new count is created and set to 1
while(true){
var count =0;
count++;
}
My first response on stack hope it helps you understand the concept a little better :)
I'm fairly sure I fixed this, instead of initializing within a while loop, I initialized it outside of the while loop and it seemed to fix this, any input on explaining the concepts behind this would be awesome!
I just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".
Please click here to view the Question and the Sample input/output (it's an image file)
Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.
Here's what I was able to come up with, so far:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int N; // number of lines of input
double length1, length2, length3; // the 3 lengths
double perimeter; // you get this by adding the 3 lengths
double minperimeter=0; // dummy value
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of triangles you have:");
N = input.nextInt();
System.out.println("Insert the lengths of the sides of these " +
"triangles (3 real numbers per line):");
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
}
System.out.printf("The minimum perimeter is %.1f%n", minperimeter);
}
}
My 2 main problems are:
1) The program only stores and works with the 'last' input.
The ones before it get replaced with this one. [update: solved this problem]
2) How do I print the "triangle number" in the final output? [update: solved this problem, too]
So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).
Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.
Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)
Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.
Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.
Change your for loop as:
double minperimeter=-1;
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
if(minperimeter == -1){
minperimeter = perimeter;
} else{
Math.min(perimeter,minperimeter);
}
}
You have to store the smaller perimeter in your variable perimeter.
The hint from your task tells you, that any given perimeter is smaller than 1000. Thus initiate the perimeter to 1000.
In your for-loop then you have to store the smaller perimeter:
perimeter = Math.min(perimeter, length1 + length2 + length3)
if the sum of the edges is smaller than the current perimeter, the smaller value will be stored.
Please note that according to your given task, you have to input 3 doubles within one line.
Alternative Solution
Make an ArrayList and add all perimeter to that list and then find the minimum value from that list.
List<Double> perimeter = new ArrayList<>();
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter.add(length1 + length2 + length3);
}
System.out.printf("The minimum perimeter is %.1f%n", Collections.min(perimeter));
Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.
I have been doing a project for my java class. For the project I have to have the user enter input and calculate their body mass index and body surface area the program is supposed to remain running until the user enters a "q". I cannot get my program to stop running when a "q" is put in it just crashes. Also I am very new to java and programming in general so I would appreciate any help. My code is as follows.
Thanks : )
public static void main(String[] args) {
//Scanner
Scanner stdIn = new Scanner(System.in);
//Variables
final double METERS_TO_CM = 100; // The constant to convert meters to centimeters
final double BSA_CONSTANT = 3600; // The constant to divide by for bsa
double bmi; // Body Mass Index
String weight; // Weight in kilograms
String height; // Height in meters
String classification; // Classifies the user into BMI categories
double bsa; // Body surface area
do {
System.out.print("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
weight = stdIn.next();
System.out.print("Enter height in meters: ");
height = stdIn.next();
double height2 = Double.parseDouble(height);
double weight2 = Double.parseDouble(weight);
bmi = weight2/(height2*height2);
if (bmi < 18.5)
{
classification = "Underweight";
}
else if (bmi < 25)
{
classification = "Normal";
}
else if (bmi < 30)
{
classification = "Overweight";
}
else
{
classification = "Obese";
}
System.out.println("Your classification is: " + classification);
bsa = Math.sqrt(((height2*METERS_TO_CM)*weight2)/BSA_CONSTANT);
System.out.printf("BMI: %.1f\n", bmi);
System.out.printf("BSA: %.2f\n", bsa);
System.out.println("Hit 'q' to quit");
} while (stdIn.nextLine().compareToIgnoreCase("q")==0);
}
}
I would guess that your "q" input is written in weight and therefore you try to parse it to a Double, which throws an unhandled Exception and stops the execution.
You should handle this Exception and make the system break the while loop when triggering it.
You're grabbing the entire line for your while loop condition.
Try just grabbing the next() instead of nextLine().
Also, you're looking at while it DOES equal 0 ... meaning equal. I'd change that to != instead. You want to continue looping while the next token is NOT Q.
Let's make a structural change to make this easier for you to do.
We are going to change it so that your do-while loop always is running, until you explicitly tell it to stop.
Your current while is:
while(stdIn.nextLine().compareToIgnoreCase("q")==0);
Which works ok, but we have a more simple way to do this. Have you heard of the break statement?
I would suggest you use break. This statement will 'break' you out of the while loop; basically it tells the program to stop looping when it is called. This will be a bit easier to follow than your somewhat confusing do-while.
do {
//Your Do code goes here, as before
...
//
//Your newly added break statement will go here.
//This breaks out of the while loop when your inputed 'choice' value is
//equal to the string of "q" (for quit)
if (Choice.equals("q"))){
break;
//When break is called nothing else in the loop will run
}
//Same thing but with the string of "quit"
if (Choice.equals("quit"){
break;
}
}while (true);
//Your new while statement is simply while(true) which will run until break is called
Hopefully that is helpful to you.
Don't actually use a loop. Since it's impractical someone would ever max the call stack out by answering too many questions, just make the whole operation a function. At the end of the function, call itself if the result isn't Q.
its simple use this
while (true)
{
Console.WriteLine("Start processing");
//processing code here
Console.WriteLine("finish processing");
Console.WriteLine("start again? y/n?");
if (Console.ReadLine().Equals("n"))
break;
}