java - can't break from do-while loop properly - java

I need to create a program that asks for numbers until the user inserts a zero and after that it should print an average of the inserted numbers. But I'm only able to get average of the first input but not the latter ones.
public static void main(String[] args) {
double a = 0;
int b = 0;
Scanner input = new Scanner(System.in);
do {
b++;
System.out.println("insert a number");
a += input.nextDouble();
}
while (a > 0 );{
}
System.out.println("the average is " + a / b );
}
}

You don't have an input in your while check. you need to have another variable called, saying userInput:
userInput = input.nextDouble();
a += userInput;
}
while(userInput > 0)
....

You are adding values from input directly to a:
a+=input.nextDouble();
So, if you add values to a directly, you can't tell when user typed in 0 and the loop will be terminated only if a drops below 0, f.e when user input is 2, 3, -5

Related

Issues with loops? Program runs as it should but test keep failing. Java using TMCbeans

I am doing an open university course in Java, it's been smooth sailing up until now. We are covering loops in this section and the problem I am stuck on asks for the following.
Write a program that reads values from the user until they input a 0.
After this, the program prints the total number of inputted values
that are negative. The zero that's used to exit the loop should not be
included in the total number count.
This is my the program I have written and I have run the program and it works as it should, however I keep getting failed test back with the following statement.
When input was: 5 4 -3 1 0 "Give a number:" text should appear a total of 5 times. Now the count was 0 expected:<5> but was:<0>
Here is my code, as I said when I run the program locally it seems to work just as asked for.
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0){
break;
}
if (number >= 1){
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
You have two problems with the code :
In the number test line,you check if a number is greater than or equal to one (number >= 1), but you should check that it is less than 0 because it is need to be negative numbers. (In the question : the total number of inputted values that are negative)
You are using with scanner.nextLine() But you don't get a line, you get a number (Int if it's integers, double if it's decimal numbers) on you to change it to : scanner.nextInt() :
Here the code :
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());// Scanner number !!
if (number == 0){
break;
}
if (number < 0){ // Less then zero !!!
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
Your problem statement says that the count of negative numbers should be the output. But what you are returning is the count of positive numbers. Change the condition from if (number >= 1) to if (number < 0).
Hope this helps.
You need the total number of inputted values that are negative. So the condition in the while loop has to change from number >= 1 to number < 0.
Check this
import java.util.Scanner;
public class NumberOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
while (true) {
System.out.println("Give a number.");
int number = Integer.valueOf(scanner.nextInt());
if (number == 0) {
break;
}
if (number < 0) {
numbers = numbers + 1;
}
}
System.out.println("number of values is " + numbers);
}
}
Also, prefer to use nextInt() because you know your input is of integer type.
I could not get the exact problem. But some observations.
If you really input all numbers at the first ask and then hitting ENTER, obviously it would throw NumberFormatException as "5 4 -3.." is not a valid number and the loop wont proceed. Try input each number and hit ENTER.
Scanner must be closed. If you are using JDK 8, use "try (Scanner scanner = new Scanner(System.in)) {...}. This would automatically close the scanner.

how to get a number to add like 12 is 3

i cant get the code right to ask for a number like 12 and then say the sum of the number is 3 in java netbeans
i got this so far
public class Exercise2_6 {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner( System.in );
System.out.println("Enter a number between 0 and 1000");
// Enter a number between 0 and 1000
Scanner input = new Scanner( System.in );
int x = in.nextInt( );
System.out.println(" The sum of the digits is "n" ");
System.out.println("n" = (in.nextInt( ) /100)); //this give you first digit
System.out.println("n" = in.nextInt( )%100); //this gives a number representing the remaining two digits
}
}
and it gives me back
run:
Enter a number between 0 and 1000
12
The sum of the digits is
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - not a statement
at Exercise2_6.main(Exercise2_6.java:55)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
Strings must be concatenated using the + operator.
Therefore, your statement of "n" = .... is not correct.
Replace
System.out.println("n" = (in.nextInt( ) /100)); //this give you first digit
System.out.println("n" = in.nextInt( )%100); //this gives a number representing the remaining two digits
with
System.out.println("n = " + in.nextInt()/100);
System.out.println("n = " + in.nextInt()%100);
However, the above statements will refer to TWO different ints, one for each time nextInt() is called. I don't know the purpose of your code but you should get into the practice of storing variables incase you need to use them again.
If you stored each int locally, for example
int n = in.nextInt();
you could then refer to it again later, for example by appending the above statements to
System.out.println("n = " + n/100); ....
This will probably not be the most efficient or 'correct' way of doing it, but I'm a complete noob myself. So, this is how I managed it. By using a while loop.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int i, a = 0, x = 0;
System.out.println("Enter a number between 0 and 1000: ");
i = input.nextInt();
while(i != 0) {
a = i % 10;
i = i / 10;
x = x + a;
}
System.out.println("The sum of the digits in your number is: " + x);
}
}

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

Right Loop for this exercise in Java

Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable

Java program high-low game

I wrote this in jQuery however the loop isn't right and I can't see my error? It doesn't end when a user inputs -99? Nor calculate the highest and lowest figure?
import java.util.Scanner;
public class LargestandSmallest
{
public static void main (String [] args)
{
//Create a Scanner object for the keyboard input
Scanner keyboard = new Scanner(System.in);
//Declare local variable
double number;
//Explain what the program does
System.out.println ("This program will ask you to enter in a series of");
System.out.println ("numbers, and then will display the lowest and");
System.out.println ("highest numbers, out of what you enter, until you input");
System.out.println ("the value indicated to end the program.");
//Have the user input a series of numbers and continue processing
//until the user enters -99
System.out.println ("Please enter a number: (or -99 to end the program).");
number = keyboard.nextDouble();
//Display the table headings
System.out.println ("Lowest\tHighest");
System.out.println ("------------------");
//Call the method to caluclate the highest and lowest numbers
calculateLowHigh(number);
}
//Module called calculateTemp
public static void calculateLowHigh(double number)
{
//Declare local calculation variables
double highestNumber = 0;
double lowestNumber = 0;
//Set the parameters for running the loop
while (number != -99)
{
for(number = 0; number < 5; number++)
{
//Calculate the lowest and highest numbers entered
if (number > highestNumber) {
highestNumber = number;
}
if (number < lowestNumber) {
lowestNumber = number;
}
}
}
//Display the results
System.out.println (lowestNumber + "\t\t" + highestNumber);
}
}
Your problem is that in calculateLowHigh, you're using the number variable for two different things. It's the parameter in which the number that the user typed is passed into this method; but you've also used it as the loop index inside the for loop. Maybe you should use a different variable for one or the other purpose. Better still, dispense with the for loop altogether - it doesn't seem to do anything.
Also, the while loop should be done in main, not in calculateHighLow, otherwise the user will only ever have the opportunity to input a number once.

Categories