Are values set inside a loop lost once the loop is over? - java

I'm doing an online course by the name of "Object-Oriented programming with Java"
And I can't figure out exercise 36..
Create a program that asks the user to input numbers (integers). The program prints "Type numbers” until the user types the number -1. When the user types the number -1, the program prints "Thank you and see you later!" and the sum of the numbers entered by the user (without the number -1).
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = 0;
int sum = 0;
while (n != -1) {
System.out.println("Type numbers");
n = Integer.parseInt(reader.nextLine());
sum = sum + n; // <-- The value set here is tossed once the loop of over?..
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum); // <-- Does not acknowledge the free state of 'loop' and any variables that come of it
}
}
So when I click the 'Run tests locally' (it's a plugin
button) in Netbeans I'm getting:
With input 1 -1 you should print "the sum is 1" expected:<1> but was:<0>
The '0', to my understanding, is indicating that the last println only recognizes the initialization of 'sum'..why is that?..

Change you while loop to check the users input as the last thing in the loop. Example:
public static void loopTest()
{
Scanner reader = new Scanner(System.in);
int n = 0;
int sum = 0;
System.out.println("Type a number then press enter... type '-1' to sum the numbers and exit");
n = Integer.parseInt(reader.nextLine());
while (n != -1)
{
sum = sum + n;
n = Integer.parseInt(reader.nextLine());
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum ); // <-- Does
}

Related

Input number then keeps reading int. values until the sum of those integer equals or become greater than the value that was input in the beginning

I had tried this logic , but it is not working, please help me to resolve the issue
import java.util.Scanner ; // USing Scanner class
class Check {
public static void main(String args[]){
//Intializing & Declaring Variables
int num ;
int sum ;
int x = 1;
// Creating object of Scanner Class
Scanner input = new Scanner(System.in);
while(x <= 100){
System.out.println("Enter an Integer"); //Prompt
num = input.nextInt(); // Taking input from User
sum = num + num ;
x = sum;
} // while lop ends
} // mainMethod ends
}// Class ends
First, prompt the user for a target value (instead of hardcoding 100). Second, add num to sum (not num to num). Third, I would display the running total. Fourth, please prefer meaningful variable names. Something like,
Scanner input = new Scanner(System.in);
// Prompt the user for a "target value"
System.out.println("Enter target value");
int target = input.nextInt();
// Initialize a running sum
int sum = 0;
// While the sum is less than or equal to the target value
while (sum <= target) {
// Prompt the user for a value
System.out.println("Enter an Integer");
// Add the value to the sum
sum += input.nextInt();
// Display the current sum
System.out.println("The current sum is " + sum);
}
// Indicate loop has completed
System.out.println("Done.");

For loop to get user input lets you enter two values for the first question, but only calculates one value

I created a small program that asks the user for 10 random numbers and it will print the sum of those numbers. I embedded it with a for loop and included a counter. Everything seems to be working fine except when I run the program, the first question allows me to enter two values, but it will still only calculate a total of 10 numbers.
Below is what I currently have and I need to understand what is going wrong when it prompts the user for the number the first time:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
sum += numberInput;
} else {
System.out.println("Invalid Number");
}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
}
}
In each loop, you're calling scanner.nextInt() and scanner.hasNextInt(). But you do not use the result of hasNextInt() in a meaningful way (you might have noticed that your "Invalid Number" output is not what happens if you enter something that's not a number).
The first call to nextInt() blocks until you enter a number. Then hasNextInt() will block again because the number has already been read, and you're asking whether there will be a new one. This next number is read from System.in, but you're not actually using it in this iteration (you merely asked whether it's there). Then in the next iterations, nextInt() will not block because the scanner already pulled a number from System.in and can return it immediately, so all the subsequent prompts you see actually wait for input on hasNextInt().
This amounts to 11 total input events: The firts nextInt() plus all 10 hasNextInt()s
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
// boolean hasNextInt = scanner.hasNextInt();
//if (hasNextInt) {
sum += numberInput;
// } else {
// System.out.println("Invalid Number");
//}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
Don't call hasnextInt() it has no use here.
It has taken 11 inputs rather than 10.
If you remove this condition it will take 10 inputs and work fine.
Your condition have no impact on it.

Averaging User Input, looping input until negative number is entered

import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.

How can I make my user aware of how many numbers they input whether it was negative or positive

So far I have this program which is already pretty close to what I want anyways. But am trying to figure out a way after the user input all his/her number he can know if he input 3 negative numbers and 4 posistive numbers
so let say he inputs -7,-8,-3,2,3,4,2 it says you have input 3 negative numbers and 4 postive numbers
import java.util.*;
public class Testing2 {
public static void main(String[] args) {
int numbers;
System.out.println("Input seven numbers");
for (int i = 1; i <8; i++){
Scanner Nums = new Scanner(System.in);
numbers = Nums.nextInt ();
if (numbers < 0){
System.out.println("You have " + numbers + " numbers that are negative");
} else {
System.out.println("You have "+ numbers + " numbers that are postive");
}
}
}
}
and what does it mean Resource leak: nums is never closed
I am using eclipse and this what shows up. Anyone know why?S
Try this:
import java.util.*;
public class Testing2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Don't need to close as System.in
int numNegative = 0, numPositive = 0;
System.out.println("Input seven numbers");
for (int i = 1; i < 8; i++){
int number = scanner.nextInt();
if (number >= 0){ // Is the number positive or 0
numPositive++;
} else { // Otherwise
numNegative++;
}
}
System.out.println("You have " + numPositive + " numbers that are positive");
System.out.println("You have " + numNegative + " numbers that are negative");
}
}
One way to do it is to use an array to keep track of your seven numbers, and two variables for keeping track of the positive or negative numbers(e.g. pos_numbers and neg_numbers),
This way, each time you receive input from the user, the if else statement tests whether the number is positive or negative, and if its positive then it will increment the pos_numbers variable by one, and if its negative then it will increment the neg_numbers variable by one. After the user is finished entering the numbers, the program will display the values of pos_numbers and neg_numbers to show how many positive numbers and negative numbers were input by the user respectively.
Also, it's a good idea to put the line where you create the Scanner object before the for loop, since this only needs to be done once instead of multiple times.
Here is the code:
import java.util.*;
class Testing2 {
public static void main(String[] args) {
int[] numbers = new int[7];
int pos_numbers = 0;
int neg_numbers = 0;
Scanner Nums = new Scanner(System.in);
System.out.println("Input seven numbers");
for (int i = 0; i <7; i++) {
numbers[i] = Nums.nextInt();
if (numbers[i] < 0) neg_numbers++;
else pos_numbers++;
}
System.out.println("You have " + neg_numbers + " numbers that are negative");
System.out.println("You have "+ pos_numbers + " numbers that are postive");
}
}

Terminating loops with strings. (Java)

Write a program that uses a while loop. In each iteration of the loop, prompt the user to enter a number – positive, negative, or zero. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters “q” to quit. When the user has finished, print the grand total and the number of entries the user typed.
I can get this program to work when I enter a number like 0, to terminate the loop. But I have no idea how to get it so that a string stops it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Your strategy would be to get the input as a string, check to see if it is a "q", and if not convert to number and loop.
(Since this is your project, I am only offering strategy rather than code)
This is the rough strategy:
String line;
line = [use your input method to get a line]
while (!line.trim().equalsIgnoreCase("q")) {
int value = Integer.parseInt(line);
[do your work]
line = [use your input method to get a line]
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
String num;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
while (!num.equals("q")) {
sum += Integer.parseInt(num);
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Cuts down on your code abit and is simple to understand and gives you exactly what you want.
could also add an if statement to check if they entered another random values(so program doesn't crash if the user didn't listen). Something like:
if(isLetter(num.charAt(0))
System.out.println("Not an int, try again");
Would put it right after the while loop, therefore it would already of checked if it was q.
java expects an integer but we should give the same exception. One way to solve this problem is entering a String, so that if the user first pressing is the Q, never enters the cycle, if not the Q. We assume that the user is an expert and will only enter numbers and the Q when you are finished. Within the while we convert the String to number with num.parseInt (String)
Integer num;
String input;
while(!input.equal(q)){
num=num.parseInt(input)
if(num<0)
sum+=1;
else
sumA+=1;
}

Categories