How to print all inputs used from loop - java

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

Related

Determining Highest Number

I am writing a program where the user must input 10 numbers and the output should be the highest number on the 10 inputs. But I don't know what's the next code that I will write.
import java.util.Scanner;
public class kzz {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int a = 1;
int value ;
while (a < 11) {
System.out.print("Enter Value No." + a + ":");
value = reader.nextInt();
a++;
}
}
}
What should I do now?
You are reading the first value into value, fine. Say it was 86. Next time through the loop you are reading the second value into the same variable, thereby overwriting the first. So the 86 are gone forever.
Instead I suggest a second variable highestValueSoFar. Store into it the value read only if it is higher. Then at the end this will contain the highest of the 10 values.

How to add multiple values with while statement?

I'm trying to ask user to type how many numbers will be inputted and enter the values then add all the values.
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
Your logic for the while loop is incorrect.
while(counter == times)
will only be true if counter and times have the same value. So if you would want to input two numbers, your while loop wouldn't even get executed. What you want is for the while loop to run until counter == times. So, your logic should be
while(counter != times)
Furthermore, you should start your counter at zero, instead of one. This is because it now means that you already inputted one number, which you didn't.
Alternatively, you could use the following snippet
while (sc.hasNextInt()) {
values += sc.nextInt()
}
This simple loop will go through all the integers inputted in the command line one by one, until there is no next integer (you type for example a letter).
In that case, you don't need to ask the user how many numbers he/she will input, as you will check it yourself.

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.

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

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

Categories

Resources