This is my first attempt at java problem I have been given as part of my Programming assignment.
I must make a program which calculates the average of a list of numbers that a user enters. the data enty should be terminated when 0 is entered. my problem is with this "ALL NEGATIVE NUMBERS SHOULD BE IGNORED"
for some reason the following code does not work, when I enter a negative number it should be ignored but for some reason it terminates the data enty
import java.util.*;
class Task_8
{
public static void main()
{
Scanner inputLine = new Scanner(System.in);
float row, numberentered, numbersum = 0, negativenumber = 0;
double result, count = 0;
System.out.println ("Welcome to Task 8 of 10 of my Programming Assignment... Nearly There!");
System.out.println ("_____________________________________________________________________");
System.out.println ();
System.out.println ("Enter as many numbers as you like and this program will tell you the arithmatic mean");
System.out.println ("Terminate data entry by entering 0");
do{
System.out.print ("Please enter a number: ");
numberentered = inputLine.nextInt();
count++;
if (numberentered < 0)
{
numberentered = negativenumber;
}
numbersum = ( numberentered + numbersum ) - negativenumber;
}
while ( numberentered !=0 );
result = numbersum/count;
System.out.println ();
System.out.println ("*************************************");
System.out.println ();
System.out.println ("The sum of all of the numbers you entered is " +numbersum);
System.out.println ("You entered " + count + " numbers");
System.out.println ("The Average/mean of the numbers that you entered is " + result);
System.out.println ();
System.out.println ("*************************************");
}
}
any Ideas guys?
Thank you
The variable negativenumber always has the value zero. When you set numberentered to negativenumber the "while" condition is met, and the loop exits. A better strategy would be to us "continue" to skip the rest of the loop body when a negative number was entered.
If you want to ignore the negative number, then don't include it in your calculation. Instead do something like:
if (numberentered > 0)
{
numbersum += numberentered;
}
Examine the following block of code:
if (numberentered < 0)
{
numberentered = negativenumber;
}
What this is doing is setting numberentered to 0. Then, at the end of your do-while loop, you have this:
while(numberentered != 0);
So, whenever the user types in a negative number, you set numberentered to zero. When you reach the end of the loop, numberentered != 0 is false, so the loop exits.
The simpler solution, and something more akin to what you will learn to do on a regular basis in the future, is to simply check the value of the number in an if statement and then add it or not based on its value.
if(numberentered > 0)
numbersum += numberentered;
This is clean, concise, and removes the need for the negativenumber variable which is superfluous and could be confusing. If you were looking at this code a year from now, would you remember what negativenumber meant, or why it was set to zero? Write your code as if somebody else will have to read it and understand it. Your professors will, and, in the future, your colleagues will.
On another note, you are reading in integers (with inputLine.nextInt()) but storing them in a float. You've also declared count as a double. You most likely will want to declare count, numberentered, and numbersum as an int.
You never assign a value other than 0 (in initialization) to negativenumber, then you do
if (numberentered < 0)
{
numberentered = negativenumber;
}
and the do...while-loop terminates because numberentered is 0.
Related
One of the questions from my Java textbook is asking me to "Create a new version of the Average program (Listing 3.6) that prevents a runtime error when the user immediately enteres the sentinel value (without entering any valid values)."
Listing 3.6 is below:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int sum = 0, value, count = 0;
double average;
System.out.println ("Enter an integer (0 to quit): ");
value = scan.nextInt();
while (value != 0) // sentinel value of 0 to terminate the loop
{
count++;
sum += value;
System.out.println ("The sum far is " + sum);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
System.out.println ();
System.out.println ("Number of values entered: " + count);
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The average is " + fmt.format(average));
}
}
I think what the question is asking is to make the sentinel value of 0 to be counted. Here is the output of Listing 3.6 when you type in the sentinel value.
Output:
Enter an integer (0 to quit):
0
Number of values entered: 0
The average is �
Additionally, I think that instead of it saying Number of values entered: 0, I think it is suppose to say Number of values entered: 1. If you think you know what the question is asking, please let me know. Thank you very much in advance.
You're getting the error because count doesn't get incremented until after you've checked the user's input. When the very first number is 0, the while loop is never entered and you end up dividing by 0. The question is asking you to fix the code so that dividing by 0 is avoided and no exception is thrown.
You need a guard to make sure count is not equal to zero.
average = (double)sum / (count == 0 ? 1 : count);
I am doing my for loop below in Java. I have a default value for the number that the user starts out with, which is 100. I dedicated a field for the user to input there own number in, which would change the default value in the constructor.
Anyway, I want my for loop to take that number that they put in and start to increment it until they reach 100. The loop runs fine but it starts at 53 and it increments I don't know why. Can someone tell me please?
My code is below.
defaultvaluenumber = userinput;
for(defaultvaluenumber = userinput; userinput < 100; userinput++)
{
System.out.println("Your current number incremented is: " + userinput);
}
Can someone tell me please? My code is below.
defaultvaluenumber = userinput;
for(defaultvaluenumber = userinput; unserinput < 100; userinput++)
{
System.out.println("Your current number incremented is: " + userinput);
}
Yes, for induction userinput contains the value 53. That's the reason!
Not really clear what you are saying about fields and constructors, but based on your later comments, the problem seems to be coming from elsewhere.
Here is what I think you are asking.
I want my for loop to take that number that they put in
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.print("Enter a starting value: ");
int userinput = sc.nextInt();
and start to increment it until they reach 100
while(userinput < 100) {
System.out.println("Your current number incremented is: " + userinput++);
}
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words,
if(num<0)
S.O.P.("You entered a negative #");
However it doesn't print it properly.
If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the num is not negative before you start the while loop.
int num = 0;
do {
if (num<0){
System.out.println("You printed out a negative number");
}
System.out.println("Enter a natural number ");
int num=type.nextInt();
} while (num<0);
Also on a side note you should probably close your scanners when you are done using them.
The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive
System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
System.out.println("The number you entered was negative!");
System.out.println("Enter a non negative number :: ");
num = type.nextInt();
}
Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZero errors or other problems. This loop should be placed before you ever use the value of num so you can make sure it is within context of your program.
The problem is that if the num is negative, it won't go inside the while loop that is because before the while loop you have initialize i=1, since any negative number is lesser than 1 the condition for while loop become false. If you want to check whether num is negative insert the if condition before the while loop as follows
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
if(num < 0) {
System.out.println("You entered a negative #");
}
else{
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
}
To answer your question .... like this:
int i = 1; // HERE
while (i <= num) {
if (num < 0) {
System.out.println("You entered a negative #");
}
fact *= i;
i++;
}
However that is not going to work.
Suppose that "num" that you read is less than zero.
At the statement labeled "HERE", we set "i" to one.
In the next statement, we test "i < num".
Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.
Since this is obviously homework, I will leave it to you to figure out what you should be doing here. But (HINT!) it is not putting the conditional inside the loop.
(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you should write Java code.)
You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:
System.out.println("Enter a natural #");
while(true){ //loop runs until broken
num = type.nextInt();
if(num>=0)
break;
System.out.println("Wrong input. Please enter a positive number");
}
The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.
Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.
I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p
Hey everyone so I've been trying to write what should be a really easy counting program for my CS class, but for some reason it keeps spitting back out the "Please enter a number (0 to stop): " prompt and seems to completely disregard the while loop. If the condition inside the while loop is being met, why does the while loop not stop even if 0 is entered? I have done C# in the past, but I'm not really familiar with Java's caveats, so if there's anything weird that Java doesn't like me to do let me know. For a more detailed description of the program, it's supposed to read both negative and positive numbers from the user, output the sum of the negatives and the positives individually, and then take the average. (Obviously below is just the problematic piece of code.)
Scanner scanner = new Scanner(System.in);
double average;
double numPositive=0.0;
double numNegative=0.0;
double input = 0.0;
do
{
System.out.print("Please enter a number (0 to stop): ");
input = scanner.nextDouble();
if (input < 0.0)
{
numNegative += scanner.nextDouble();
}
else if (input > 0.0)
{
numPositive += scanner.nextDouble();
}
} while (Math.abs(input) > 1.0e-6); // make the tolerance whatever you want.
You never change input after the initial assignment; the loop will continue on forever. I think you forgot to call scanner.nextDouble() again.
You're not taking in input after initially retrieving it.
Your scanner.nextDouble() assigns to numNegative and numPositive- neither of which is checked by the while loop.
while (input != 0.0)
{
System.out.print("Please enter a number (0 to stop): ");
input = scanner.nextDouble();
if (input < 0.0)
{
numNegative += input;
}
else if (input > 0.0)
{
numPositive += input;
}
}
You are not assigning a value to input anywhere inside your loop. So, the initial value remains, and the loop won't exit.