Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!
Related
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.
I'm trying to learn (self-taught) Java by reading Big Java, Late Objects from by Cay Horstmann. I'm using repl.it to write my code (if you may want to look it up, it's public)
A selfcheck question of Chapter 4 Loops is:
How can you overcome the problem of when the user doesn't provide any input in the algorithm of section 4.7.5 (titled Maximum and Minimum) and the WHILE loop just terminates the program for this reason ?
They basically ask to rewrite the code so it solves this problem.
The information of section 4.7.5 you need to solve this problem: To compute the largest value in a sequence, keep a variable that stores the largest element that you have encountered, and update it when you find a larger one.
(This algorithm requires that there is at least one input.)
double largest = in.nextDouble();
while (in.hasNextDouble())
{
double input = in.nextDouble();
if (input > largest)
{
largest = input;
}
}
This is what the book suggests as the answer to this problem (but I disagree):
One solution is to do all input in the loop and introduce a Boolean variable that checks whether the loop is entered for the first time.
double input = 0;
boolean first = true;
while (in.hasNextDouble())
{
double previous = input;
input = in.nextDouble();
if (first) { first = false; }
else if (input == previous) { System.out.println("Duplicate input"); }
}
I don't fully understand the first sentence. And I disagree this as a solution for the problem because (as far as I can tell) it tests whether the input has been entered before, instead of testing if any sort of user input has been provided..
I tried to merge those two sections of code together but I can't seem to make it work. Or more specific: figure out how to build it. What variables / loops do I need? In which order do I write this?
I've made a flowchart in Visio of the first section of code but have no clue how to continue.
This is what I've written so far:
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number: ");
double largest = 0;
while (input.hasNextDouble())
{
double value = input.nextDouble();
if (value > largest)
{
largest = value;
System.out.println("The largest input till now is: " + largest);
}
}
Can someone:
Ask me questions which help me to solve this question? I.e. Tell me what tools I need (WHILE, FOR etc.)
Provide a solution in text which I can hopefully transform in code
Or write the code for me (I haven't learned arrays yet, so please solve it without)
Thanks in advance,
So I worked on this for a bit and I think I have something close to what you're looking for using a do while loop.
This code accepts user input first, then checks it's value in comparison to the last input and return either "Input a higher value", "Duplicate number found", or it sets the last number entered to the current number.
I hope this helps you get your code to where you'd like it to be! I'm still new, so I apologize if this is not entirely optimized.
Also, I have not added a way to exit the loop, so you may want to add a check on each iteration to see if the user would like to continue.
public static void main(String[] args) {
double userInput = 0;
double prevNum = 0;
boolean hasValue = false;
boolean exitCode = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
userInput = sc.nextDouble();
do {
if (userInput<prevNum) {
System.out.println("Please enter a number higher than " + prevNum);
hasValue=true;
}
else if (userInput==prevNum) {
System.out.println("Duplicate input detected.");
hasValue=true;
}
else {
prevNum = userInput;
hasValue = true;
}
}
while(hasValue==false);
System.out.println(prevNum);
System.out.println(userInput);
}
while(exitCode==false);
}
If you want compute if the number entered is the largest entered from the beginning but declare it at the largest if it's the first iteration then do this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean flag = true;
double largest = 0;
System.out.println("Enter the number: ");
while (input.hasNextDouble()){
double value = input.nextDouble();
if (flag) {
flag = false;
largest = value;
}
else if (value > largest) largest = value;
System.out.println("The largest input till now is: " + largest);
System.out.println("Enter a new number: ");
}
}
I am making an odd or even program with a while loop. I am trying to figure out how to end the while loop with a certain number. Right now I have 1 to continue the loop, and trying to make 2 the number that terminates it. Also trying to figure out how to terminate the program if a user types anything but a number like a letter/words.
package oddoreven;
import java.util.Scanner;
public class oddoreven {
public static void main (String[] args){
int num;
int x = 1;
while(x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
You should try to use "a real termination condition" in order to terminate a while loop (or any loop for that matter); it's cleaner and should be easier to understand by everyone else.
In your case, I think it's better to have a do-while loop with some condition around this logic: num % 2 == 0, and an inner while loop for handling user input/validation.
If you still want to break loops abruptly, have a look here.
If you still need some help with the code, hit me up and I'll sketch up something.
I did not follow the conditions you wanted exactly because it does not make sense to have a continue condition AND a terminate condition unless there are other options.
What did you want the user to do if he entered 3, 4 or 5? Exit the code or continue the code? Well if the default is to exit, then you do not need the code to exit on 2 because it already will! If the default is to continue, then you do not need the continue on 1 and only the exit on 2. Thus it is pointless to do both in this case.
Here is the modified code to use a do while loop to ensure the loop is entered at least 1 time:
int x;
do {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
//trying to figure out how to get the code to terminate if you put in a value that isn't a number
System.out.println("Type 1 to check another number, anything else to terminate.");
if (!s.hasNextInt()) {
break;
}
else {
x = s.nextInt();
}
} while(x == 1);
}
Note that I added a check to !s.hasNextInt() will check if the user enters anything other than an int, and will terminate without throwing an Exception in those cases by breaking from the loop (which is the same as terminating the program in this case).
If the x is a valid integer, then x is set to the value and then the loop condition checks if x is 1. If x is not 1 the loop terminates, if it is it will continue through the loop another time.
Another thing you can try is that instead of exiting the program you can just keep asking user to enter correct input and only proceed if they do so. I don't know what is your requirement but if you want to go by good code practice then you shouldn't terminate your program just because user entered wrong input. Imagine if you googled a word with typo and google just shuts off.
Anyways here is how I did it
import java.util.Scanner;
public class oddoreven {
public static void main(String[] args) {
int num;
int x = 1;
while (x == 1) {
System.out.println("Enter a number to check whether or not it is odd or even");
Scanner s = new Scanner(System.in);
boolean isInt = s.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
s.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
num = s.nextInt(); // If it is int. It reads the input
if (num % 2 == 0)
System.out.println("The number is even");
else
System.out.println("The number is odd");
// trying to figure out how to get the code to terminate if you put in a value
// that isn't a number
System.out.println("Type 1 to continue, 0 to terminate");
x = s.nextInt();
}
}
}
To exit the program when the user enters anything other than a Number, change the variable x type to a String
if (!StringUtils.isNumeric(x)) {
System.exit(0);
}
To exit the program when user enters 2
if (x == 2) {
System.exit(0);
}
So for my Java programming class one of the assesments is the following (a classic number guessing game):
Write a program that plays the HiLo guessing game with
numbers. The program should pick a random number between 11 (inclusive) and 88 (exclusive), then
repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is
correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or
choose to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of
guesses and report that value when the user guesses correctly. At the end of each game (by quitting or
a correct guess), prompt to determine whether the user wants to play again. Continue playing games
until the user chooses to stop. You are required to utilise at least a while loop and a for loop correctly.
So far, the game is fully working, using WHILE and IF functions. But in order to get full marks on my solution, it requires me to use at least one FOR loop, but I'm struggling to do that.
import java.util.*;
public class Guessing {
public static void main (String[] args)
{
//Setting up the variables
final int MAX = 88;
final int MIN = 11;
int answer, guess = 1;
String another="Y";
//Intializing scanner and random
Scanner scan = new Scanner (System.in);
Random generator = new Random();
//play again loop
while (another.equalsIgnoreCase("Y"))
{
//Generate a random number between 11 and 88
answer = generator.nextInt(MAX-MIN)+11;
System.out.print ("Guess the number I picked between "+MIN+" and "
+ MAX + "!\n");
while(guess!=answer)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!");
break;}
}
}
//Asking player to play another game
System.out.println("Do you want to play another game?(Y|N)");
another = scan.next();
if (another.equalsIgnoreCase("N"))
System.out.println("Goodbye, thank you for playing");
}
}
}
So far, the program works. It correctly gives higher/lower advice, the current round stops when typing in 0 as a guess and you can start another round with Y/N. But Im struggling to substitute one of the functions/loops with a FOR loop.
You can substitute the central while loop with a for loop that you can also use to count the number of iterations
for(int i=0;;i++)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!\n");
System.out.println("It took "+i+" guesses to get the answer");
break;}
}
}
This for loop is an infinite loop because it hasn't got the second argument. However your program will exit the for loop when the correct answer is given because of the break in the final else.
As the number of guesses is counted upwards, one may use the for loop on that.
Normally one would write for (int i = 0; i < n; ++i) { but here we want to know the loop counter after the for loop and have to declare it before:
int numberOfGuesses = 0;
for (; guess != 0 && guess != answer; numberOfGuesses++) {
}
... numberOfGuesses
There is no upper limit other than finding the answer or quiting.
All three parts in for (PARTA; PARTB; PARTC) are optional.
import java.util.Scanner;
public class MyFirstGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double randomNumber = Math.random();
double realNumber = randomNumber*10;
double realerNumber = Math.round(realNumber);
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
}
So what I am trying to do is make a "game" for my Java class. I have generate a random number between 1 and 10 and the user has to input a number and if the input and the random number are the same, they "win." If they lose, they try again...? First, I did all the necessary scanner stuff that I don't even fully understand. I just copied the professor. So the program says to enter a number and the program generates a number between 0.0 and 1.0. I multiply that number by 10 to make it between 1 and 10. Then I round the number to the nearest integer. If the input matches this number, the program says you win. If not, it'll say try again.
The problem is how do I make the program repeat itself without the user having to reboot the program with the cmd? I need to repeat the input, random number generator, and then the result. What do I need to do? Also, how is my program? My second big one...yeah right...big. But seriously, how can I make it less complex or anything to improve it. Thanks.
Use a while loop:
long realerNumber = Math.round(realNumber);
// first guess
long guess = scanner.nextLong();
while (guess != realerNumber) {
System.out.println("Try Again...");
// guess again
guess = scanner.nextInt();
}
System.out.println("You Win!");
There is already a class to generate random numbers, you could use it:
// TODO: move to constant
int MAX = 10;
// nextInt(int n) generates a number in the range [0, n)
int randomNumber = new Random().nextInt(MAX + 1)
just put your code inside the do-while loop
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double realerNumber = Math.round( Math.random() * 10 );
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
while(someCondition);
the someCondition can be for example a counter (if you want to play n times just set counter to n and decrease it every loop iteration then check if it is 0 in while) or some function checking if a key is pressed (like escape)
int n = 5;
do
{
n--;
...
}
while(n > 0);
This will run forever, but it's the idea mentioned in the first comment
...
Scanner scanner = new Scanner(System.in);
while(true){ // add this after Scanner ... declaration
...
} // end of existing else block
} // end of while loop, so add this single brace
...