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.
Related
i've just started java programming and was wondering on how to approach or solve this problem i'm faced with.
I have to write a program that asks a user for a number and continually sums the numbers inputted and print the result.
This program stops when the user enters "END"
I just can't seem to think of a solution to this problem, any help or guidance throughout this problem would be much appreciated and would really help me understand problems like this. This is the best i could do
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int x = scan.nextInt();
System.out.print("Enter a number: ");
int y = scan.nextInt();
int sum = x + y;
System.out.println("Sum is now: " + sum);
}
}
}
The output is supposed to look like this:
Enter a number: 5
Sum is now: 5
Enter a number: 10
Sum is now: 15
Enter a number: END
One solution would be to not use the Scanner#nextInt() method at all but instead utilize the Scanner#nextLine() method and confirm the entry of the numerical entry with the String#matches() method along with a small Regular Expression (RegEx) of "\d+". This expression checks to see if the entire string contains nothing but numerical digits. If it does then the matches() method returns true otherwise it returns false.
Scanner scan = new Scanner(System.in);
int sum = 0;
String val = "";
while (val.equals("")) {
System.out.print("Enter a number (END to quit): ");
val = scan.nextLine();
// Was the word 'end' in any letter case supplied?
if (val.equalsIgnoreCase("end")) {
// Yes, so break out of loop.
break;
}
// Was a string representation of a
// integer numerical value supplied?
else if (val.matches("\\-?\\+?\\d+")) {
// Yes, convert the string to integer and sum it.
sum += Integer.parseInt(val);
System.out.println("Sum is now: " + sum); // Display Sum
}
// No, inform User of Invalid entry
else {
System.err.println("Invalid number supplied! Try again...");
}
val = ""; // Clear val to continue looping
}
// Broken out of loop with the entry of 'End"
System.out.println("Application ENDED");
EDIT: Based on Comment:
Since since an integer can be signed (ie: -20) or unsigned (ie: 20) and the fact that an Integer can be prefixed with a + (ie: +20) which is the same as unsigned 20, the code snippet above takes this into consideration.
Do it like this:
public static void main(String[] args) throws Exception {
int sum = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.print("Enter a number: ");
if (scan.hasNextInt())
sum += scan.nextInt();
else
break;
System.out.println("Sum is now: " + sum);
}
System.out.print("END");
}
This will end if the input is not a number (int).
As pointed out in the comments, if you want the program to stop when the user specifically enters "END", change the else-statement to:
else if (scanner.next().equals("END"))
break;
i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"
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);
This program should take a user defined number, create an array of that size and let the user input the elements - which are grades - using a do..while loop. The program then needs to display all grades entered from lowest to highest, accumulate the grades, and find the average.
My output isn't displaying the entered grades correctly (if I enter 10,20,30, it displays 00,10,20) and I can't figure out what I'm doing wrong. Any help, please?
import java.util.Arrays;
import java.util.Scanner;
public class LoopArray
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
int count = 0;
double totalAverage = 0;
double gradesTotal = 0;
System.out.println("Please input the number of grades you would like to submit for an average: ");
int numberOfGrades = keyboard.nextInt();
int[] studentScores = new int[numberOfGrades];
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Arrays.sort(studentScores);
for(count=0; count < studentScores.length; count++)
{
System.out.println("Grades entered were: " + count + studentScores[count]);
}
totalAverage = gradesTotal / numberOfGrades;
System.out.println("The total of all grades entered is: " + gradesTotal);
System.out.println("The average of grades entered is: " + totalAverage);
}
}
Result
Grades entered were: 00
Grades entered were: 10
Grades entered were: 20
is generated with
System.out.println("Grades entered were: " + count + studentScores[count]);
So last number in each line is pair representing count + studentScores[count]. This means that:
00 -> at position 0 array studentScores stores 0.
10 -> at position 1 array studentScores stores 0
20 -> at position 2 array studentScores stores 0
Which means you didn't fill your studentScores array with values from user.
You are not putting any value inside the array. You need to add this to your do part of the loop studentScores[count] = inputGrade;
Now your do while loop should look like this:
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count] = inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Also, inside your last for-loop, you are printing extra info. Just remove that count from System.out.println
System.out.println("Grades entered were: " + studentScores[count]);
Anything you don't understand let me know thanks
Because count start from 0. You should check it.
you forgot to populate the array using the gardes entered
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count]=inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
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