How to make a sentinel value become a valid value in Java? - java

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);

Related

range between the min and max value

Create a NumberInTheRange application that prompts the user for two numbers.
The first number is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. Be sure to include the min and max numbers in the prompt.
I wrote a code allowing the users to write the two min and max values. However, I am wondering what code should I write in order to fulfill the conditions above. I am thinking about using loops and it would be very helpful if you guys correct me and give some instructions on how to process these.
import java.util.Scanner;
public class NumberinTheRange {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type two numbers:");
int n1=scan.nextInt();
int n2=scan.nextInt();
}
}
Use a do...while loop.
int num;
do {
System.out.println("Enter a number between " + n1 + " and " + n2 + ":");
num = scan.nextInt();
} while(num < n1 || num > n2);
Now, you need to put a condition to loop-back if the input is not in the range. You can use a do-while loop for the same. You can do it with any other loop but using a do-while loop guarantees that its body will be executed at least once.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Type two numbers: ");
int min = scan.nextInt();
int max = scan.nextInt();
int n;
do {
System.out.print("Enter a number in the range of " + min + "-" + max + ": ");
n = scan.nextInt();
} while (n < min || n > max);
System.out.println("Your number is: " + n);
}
}
A sample run:
Type two numbers: 10 20
Enter a number in the range of 10-20: 34
Enter a number in the range of 10-20: 5
Enter a number in the range of 10-20: 15
Your number is: 15

How to print all inputs used from loop

I am trying to have an output where the entered numbers in the loop are all printed out as separate numbers. Example: Entered numbers: 10, 15, 1, 25.
Here is my code:
import java.util.Scanner;
public class SumofNumbersAbove0 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
int input;
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
input = scan.nextInt();
}
System.out.println("Entered Number: " + input);
System.out.println("The sum: " + number);
}
}
I get the sum of all the numbers correctly. But all I get for entered numbers is the final one.
Move your print of input into the loop where each value of input is actually present. Where you have it you only get the last input
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
System.out.println("Entered Number: " + input);
input = scan.nextInt();
}
System.out.println("The sum: " + number);
Issue:
In your code the two variables you have input and number (which should rather be named sum) are solving very different purpose. input is acting a transient pedestrial where the user-entered values come and land. From there the value is added into number and then come another user-entered value which lands onto the same pedestrial thereby knocking-off the previous value.
Thus when you print input at the bottom of your code, the value you find is the one which came last to the pedestrial (which in your case is some integer < 0)
Solution: What you want is to perform an operation (print) on each of the input values. You can do either of the following-
Perform the operation before losing the value. I mean print the value in the loop itself. Adding the value to number is another operation you are already doing before losing the value
Persist all the input values. Here you need to have some bigger pedestrial which can accomodate all the incoming user-entered value without knocking-off previous values. Once you have all the them you can revisit the values and operate on them. printing them could be one operation and accumulating their values in another variable number could be another.
Hope that helps

sentinel value and displaying my results

I've been trying to figure out my code for hours and I know this is probably something simple but I would really appreciate some help!
Here's my problem:
// Purpose: This program will prompt the user to enter a positive integer.
// The program will accept integers until the user enters a -1.
// Once the -1 is entered, the program will display the integers followed
// by their sum.
import java.util.Scanner;
public class InputSum
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// variable declaration
int inputNumber;
int stringNumber = 0;
int num = 0;
int sum = 0;
// prompt user to enter an integer
System.out.print("Enter a positive integer: ");
inputNumber = scan.nextInt();
// continue to have user enter integers until:
while (inputNumber >= 0)
{
sum += inputNumber;
stringNumber = inputNumber++;
System.out.print("\n Enter another positive integer (enter -1 to quit): ");
inputNumber = scan.nextInt();
// -1 is entered
if (inputNumber == -1)
{
break;
}
}
// display results
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
System.out.print("\n The sum of the intergers are: " + sum);
}
}
Right now my results are showing my sum correctly, but it's supposed to display the integers I enter in a line separated by commas. (EX: if the user enters 1, 1, 1 my results should be The integers you entered were: 1, 1, 1 The sum of the integers are: 3). And right now it's adding my integers entered to the sentinel value and displaying my results as: The integers you entered were: 1.
I'm really stuck on how to do this. Any suggestions? Thanks!
You must store the input each time.
Replace
stringNumber = inputNumber++;
by
stringNumber += inputNumber+", ";
This will store the inputs in inputNumber.
Change
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
into
System.out.print("\n The integers you entered were: " + stringNumber);
This will display all inputs entered.
You are only printing the last number you entered :
System.out.print("\n The integers you entered were: " + Integer.toString(stringNumber));
If you wish to print all the input numbers, you have to store them somewhere.
If you wish to store them in stringNumber, change its type to StringBuilder, and append each number to it.
StringBuilder stringNumber = new StringBuilder();
...
stringNumber.append(inputNumber);
stringNumber.append(", ");
...
System.out.print("\n The integers you entered were: " + stringNumber.toString());
You'll have to make a slight adjustment to this code, in order to avoid printing an extra "," after the last number.

Checking for negative values with scanner in

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

Finding the Average from a list of numbers in Java

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.

Categories

Resources