How to correct my sentinel value? - java

My code is supposed to ask for a name, ask for a number between one and ten, print the numbers from 1 to the number the user entered except every third number should
be the user's name that was entered at the beginning of the program, print the even numbers, continually ask the user for numbers until the user enters the sentinel, and then print the total of the numbers entered. (I know, that's a lot.) My code is running fine, the only problem I am having is with the last part. Even when the user enters the sentinel, which in this case is -1, the program still asks for another entry.
Did I do something wrong when declaring the variable or can someone explain how to fix my problem? Here is my code.
import java.util.Scanner;
/**
*
* #author Home
*/
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();
System.out.print( "Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print( "No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
System.out.println(" Enter a number or -1 to finish. " );
inputNumber = scan.nextInt();
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println( "The total is " + total);
}
}

Solution:
You get input from user and saving that input in varible called number but you are checking your while against inputNumber.
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
inputNumber = scan.nextInt(); <<< not number should be inputNumber
}

public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for (int i = 2; i <= number; i += 2) {
System.out.print(i + " ");
}
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
do {
System.out.println(" Enter a number or -1 to finish. ");
inputNumber = scan.nextInt();
if(inputNumber!= SENTINEL){
total+=inputNumber;
}
} while (inputNumber != SENTINEL);
System.out.println("The total is " + total);
}
}

Related

How do I output the number loops in after a while()?

Im trying to get the output for the number of times the loop was ran over, decided by the user. Im using while() but I'm not sure how to output the number of loops once the loop is over.
Here's my code:
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
int number1 = input.nextInt();
System.out.println("You Chose Number " + number1);
while (number1 != 1) {
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
}
}
please help me thank you !!
You just need an additional variable that increments each time the loop occurs. Then after the loop you can use that variable to show the number of times looped.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
int number1 = input.nextInt();
int loopcount = 0;
System.out.println("You Chose Number " + number1);
while (number1 != 1){
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
loopcount += 1;
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
System.out.println("Looped " + loopcount + " times";
}
By the way, you could also optimise the function by eliminating the input request before the "while()" loop. It's repeated, redundant code that doesn't need to be there.
For example:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number1 = 0;
int loopcount = -1;
while (number1 != 1) {
System.out.println("Choose a number between 2 and 10, choose 1 to end it");
number1 = input.nextInt();
loopcount += 1;
System.out.println("You Chose Number " + number1);
}
System.out.println("Thank you for choosing. Goodbye");
System.out.println("Looped " + loopcount + " times";
}
If there is only requirement to count the looping then taking an int variable is enough, but if you want to keep records the chosen number then take a List which can store the chosen numbers dynamically and its length would be the looping count.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice = 0;
int count=0;
List<Integer> numbers = new ArrayList(); // if chosen num is needed
do{
System.out.print("Choose a number between 2 and 10, choose 1 to end it :");
choice = scanner.nextInt();
if(choice !=1 ) {
count++;
numbers.add(choice); // if chosen num is needed
}
}while (choice != 1);
System.out.println("Loop counts " + count);
System.out.println("Loop counts " + numbers.size() + " times and numbers are "+numbers);
}

How to make integer input appear after rather than before message that prompts user input?

I was creating a program in which the user is repeatedly asked to enter input until the Scanner reads 0. For some odd reason whenever I enter an integer, it appears before the next message appears asking for input.Any help to resolve this is much appreciated.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer, the input ends if it is 0: ");
int number;
int posCount = 0;
int negCount = 0;
int total = 0;
while((number = input.nextInt()) != 0) {
System.out.println("Enter an integer, the input ends if it is 0:");
if(number < 0) {
negCount++;
}
if(number > 0) {
posCount++;
}
total += number;
}
System.out.println("The number of negatives is " + negCount);
System.out.println("The number of positives is " + posCount);
System.out.println("The total is " + total);
Do use System.out.print() isntead of System.out.println().
System.out.print("Enter an integer, the input ends if it is 0: ");

Have trouble with a while loop and trying to terminate the program by a press of a letter

I have a problem with my program.
Program is a HILO game which requires the user to guess a number between a range of a generated number.
The problem is that once i press 0 on my keyboard, it reveals the random number, and essentially must end the loop and ask whether the user wants to continue or end the program. Instead, it continues the loop, and whenever I press a letter on the keyboard it shows me an Exception error which describes and input Miss Match. Can some one guide me on how to fix it?, maybe I wrote the program wrong, I tried multiple ways, it still doesn't work as it supposed to work.
Thank you.
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class HILOGAME
{
public static void firstGame()
{
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
for (int exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.nextLine();
if (!choice.equalsIgnoreCase("x"))
{
Loop = true;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
Loop = false;
System.out.print("END OF GAME");
exit = 11;
}
}
if (number > answer)
{
System.out.println("TOO HIGH");
}
if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
}
}
}
}
}
EDIT 1:
This code is working perfectly for me i have tried running it:
final int range = 50;
int answer = 0;
int guesses;
int number;
int guessNum = 0;
String choice = "";
boolean Loop = false;
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.println("IF YOU WISH TO GIVE UP, PRESS 0 ON THE KEYBOARD");
while (!Loop)
{
int exit;
for (exit = 0; exit < 10; exit++)
{
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
guessNum = guessNum++;
guessNum += 1;
if (number == answer)
{
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
System.out.println("Enter x to continue to play or y to endgame");
choice = input.next();
// HERE YOU ARE DOING THE WRONG THING
// What is the meaning of "not(!)" here ? !choice.equalsIgnoreCase("x")
// Remove "NOT(!)" from here your program will work as expected
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
else if (number > answer)
{
System.out.println("TOO HIGH");
}
else if (number < answer)
{
System.out.println("TOO LOW");
}
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter x to continue to play or y to endgame");
// MADE CHANGES HERE
choice = input.next();
if (choice.equalsIgnoreCase("x"))
{
//here you should assign loop to false if they continue
Loop = false;
answer = r.nextInt(range) + 1;
System.out.print("A new number");
break;
}
else if (choice.equalsIgnoreCase("y"))
{
//better to insert break here as well
//here you should assign loop to true if they wanna exit.
Loop = true;
System.out.print("END OF GAME");
exit = 11;
break;
}
}
}
}
Please do copy-paste the code. Because it is working perfectly without any Exception..!!
My sample outputs:
SAMPLE 1:
Guess a number between 1 and 50 : 1
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 27
Enter x to continue to play or y to endgame
y
END OF GAME
SAMPLE 2:
Guess a number between 1 and 50 : 20
TOO HIGH
Guess a number between 1 and 50 : 19
TOO HIGH
Guess a number between 1 and 50 : 15
Your guess was correct
The number was: 15
You guess the number with: 3 guesses
Enter x to continue to play or y to endgame
x
A new numberGuess a number between 1 and 50 : 20
TOO LOW
Guess a number between 1 and 50 : 0
TOO LOW
YOU GAVE UP. THE NUMBER WAS 42
Enter x to continue to play or y to endgame
y
END OF GAME
Do let me know if there is any problem.
Well, if you wish to end a loop, you could use the break; command. It jumps out of a while or for loop. So you could use this if the number is 0:
if (number == 0)
{
System.out.println("YOU GAVE UP. THE NUMBER WAS " + answer);
System.out.println("Enter 'x' to continue to play or y to endgame");
choice = input.nextLine();
if(choice == "y")
{
break;
}
and add:
if(choice == "y") {break;} to the very end of the while(!Loop) loop.
And with the time when the answer is correct, you set Loop to false, which means !Loop would evaluate to true. You should change Loop = false to Loop = true when they decide to continue the game.
a small modification
public class HILOGAME {
public static void firstGame() {
final int range = 50;
int answer;
int number;
int guessNum = 0;
String choice = "";
Scanner input = new Scanner(System.in);
Random r = new Random();
answer = r.nextInt(range) + 1;
System.out.print("Guess a number between 1 and " + range + " : ");
number = input.nextInt();
if (number == answer) {
System.out.println(" Your guess was correct ");
System.out.println();
System.out.println("The number was: " + answer);
System.out.println("You guess the number with: " + guessNum + " guesses ");
System.out.println();
} else {
System.out.println("you entered a wrong value");
System.out.println("do you really want to try again? press y to continue or other alphabet to exit");
choice = input.next();
playAgain(choice);
}
}
public static void playAgain(String choice) {
if (choice.equalsIgnoreCase("Y")) {
firstGame();
} else {
System.out.println("you chose to quit");
System.exit(0);
}
}

Taking scanner input and outputting min and max

so I'm trying to find the min, max, and average number of the numbers input. Everything works fine, although I do not want input less than 0 or greater than 100. When I input a number less than 0 or greater than 100 it still records it as the min/max. I do not want this! How would I not take input that is less than 0 or greater than 100?
Thanks!
import java.text.DecimalFormat;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[]args){
Scanner scan = new Scanner(System.in );
int number = 0;
double total = 0;
int minimum;
int maximum = 0;
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
minimum=number;
total += number;
for(int i = 2; i<11; i++){
if(number<0 || number >100){
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
i--;
}
else{
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
total += number;
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + minimum);
System.out.println("The maximum is: " + maximum);
System.out.println("The average is: " + oneDecimalPlace.format((total) / 10.0 ));
}
}
Let's say you entered 5 for integer one, then 102 for the second integer. What's going to happen? Well before you entered 102, number was 5, so it will go into the else block.
It'll say:
Please enter integer 2:
then you type: 102
So then what? Well the next piece of code is:
number = scan.nextInt(); and then it goes through the if-statements right below it to determine if it's a maximum. Nothing is stopping it.
Try this code instead of your loop:
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
// keep them in a loop until they enter a valid number
while (number < 0 || number > 100) {
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
}
// after they entered a valid number, add it to the series
minimum = number;
total += number;
for(int i = 2; i < 11; i++) {
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
// keep them in a loop until they enter a valid number
while (number < 0 || number > 100) {
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
}
// after they entered a valid number, add it to the series
total += number;
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
problem:
if(number<0 || number >100)
It will return false when number is 100 or 0 thus accepting it and executing you else block.
Is 100>100 answer false because they are equal, not greater than the other
solution:
if(number<1 || number >99)
EDit:
public static void main(String[]args){
Scanner scan = new Scanner(System.in );
int number = 0;
double total = 0;
int minimum = 0;
int maximum = 0;
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
if(number>1 && number <99)
{
minimum=number;
total += number;
}
for(int i = 2; i<11; i++){
if(number<1 || number >99){
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
i--;
}
else{
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
total += number;
if(number>1 && number <99)
{
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + minimum);
System.out.println("The maximum is: " + maximum);
System.out.println("The average is: " + oneDecimalPlace.format((total) / 10.0 ));
}
Here is an Example.Exceptions are not handled so put a Try-catch to String to Integer Conversion If you want.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Numbers{
public static void main(String x[]){
Scanner scn=new Scanner(System.in);
int Total=0,Max=0,Min=Integer.MAX_VALUE;
for(int i=0;i<10;){
System.out.print("Enter Number :");
int NumberOne=Integer.parseInt(scn.nextLine());//Put a Try catch If needed
if(NumberOne>0&&NumberOne<100){
Total+=NumberOne;
Max=(Max>NumberOne)?Max:NumberOne;
Min=(Min<NumberOne)?Min:NumberOne;
i++;
}else{
System.out.print("Number Invalid");
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + Min);
System.out.println("The maximum is: " + Max);
System.out.println("The average is: " + oneDecimalPlace.format((Total) / 10.0 ));
}
}

infinite loop when asking for number

Hi all thanks for taking the time, I am continuosly getting an infinate loop when i am inserting the variable m could anyone please take a look thanks.
public static void main program7_2(String args [])
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while((n%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while((m%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum =0;
for (int i = n; n<=m; i++)
{
if ((i%2) != 0)
sum = sum + i;
}
System.out.println("Sum of the numbers between "+n+ " and " +m+": " + sum);
}
The problem of the program is to enter 2 odd numbers and get the sum of the odd numbers in between
Thanks and regards
Instead of n<=m in your for loop use i<=m since you are using i as your counter and not n
This is the error :
for (int i = n; n<=m; i++) /* terminating condition "n<=m" is never met here */
{
if ((i%2) != 0)
sum = sum + i;
}
Why : this loop increments i but terminating condition is n<=m which is never met....so either do i<n Or i<m which ever suits you for terminating the condition!!
if u want to get the sum of nubers between those two use
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while ((n % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while ((m % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum= 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("Sum of the numbers between " + n + " and " + m + ": " + sum);
}
}

Categories

Resources