How do I end the loop completely after I input "q"? - java

The program does not stop after I input "q"; it still prints the random number and the sum of it. I want the program to completely stop right after I input "q".
import java.util.Scanner;
import java.util.Random;
public class lab7
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
String letter = " ";
int num = 0;
System.out.print("Push your luck");
*/the program prints push your luck!
while(!letter.equals("q")){
int sum = rand.nextInt(12);
System.out.println(" ");
letter = input.nextLine();
*/ the program should not print random number or sum when input "q"
*/but in this case it does
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}
}
}

First give your variables meaningful names. So num should be sum and sum shoud be num.
Next rearrange your code inside the loop like this:
Scanner input = new Scanner(System.in);
Random rand = new Random();
String letter = " ";
int sum = 0;
System.out.print("Push your luck");
while (!letter.equals("q")) {
int num = rand.nextInt(12);
System.out.println(" ");
letter = input.nextLine();
if (!letter.equals("q")) {
sum = sum + num;
System.out.println("Random number: " + num);
System.out.println("Updated number: " + sum);
}
}
The if statement inside the loop prevents any further code from being executed when entered q.

Looks like you want to do:
letter = input.nextLine();
while(!letter.equals("q")) {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
letter = input.nextLine();
}

Just move the input to the last line of the loop, and add an input just before. That way your loop condition is always checked immediately after the input has been received.
letter = input.nextLine();
while(!letter.equals("q")){
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
letter = input.nextLine();
}

A for loop should do.
for(String aletter = input.nextLine();!aletter.equals("q");aletter=input.nextLine()) {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}
And well as you dont use the input it can be simplified:
while(!input.nextLine().equals("q")) {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}
And if you wanted at least one output before you are able to stop it with "q":
do {
int sum = rand.nextInt(12);
System.out.println(" ");
System.out.println("Random number: " + sum);
System.out.println("Updated number: " + num);
num = num + sum;
}while(!input.nextLine().equals("q"));

You can make an if clause which checks if q was entered and use the break; statement to stop it. The continue statement would also work for this case.

Related

Printing Common Divisors of Inputted Positive Integers

I need to print the common divisors between two positive integers that were entered. They need to be printed in ascending order. If they are relatively prime, "1" needs to be printed. The code I have here is nowhere near correct. I'm really confused on how to use the loops properly while keeping it in ascending order.
Sample input:
Integer a: 8 Integer b: 12
Sample Output:
Common divisors of 8 and 12:
1
2
4
8 and 12 are not relatively prime.
Alternate Input:
Integer a: 8 Integer b: 9
Common divisors of 8 and 9:
1
8 and 9 are relatively prime.
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = scnr.nextInt();
int num2 = scnr.nextInt();
System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
int div1 = 0;
int div2 = 0;
int same = 0;
for (int i=1;i<=num1;i++) {
while (div1 <= num1) {
div1 = num1/i;
}
while (div2 <= num2) {
div2 = num2/i;
}
if (div1 == div2) {
div1 += same;
System.out.println(same);
System.out.println(num1 + " and " + num2 + " are not relatively prime.");
}
if (div1 != div2) {
System.out.println(1);
System.out.println(num1 + " and " + num2 + " are relatively prime.");
}
}
}
}
You can try something simple like the below:
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1 = scnr.nextInt();
int num2 = scnr.nextInt();
System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
for(int i = 1; i<= Math.min(num1,num2); i++){
if(num1%i==0 && num2%i==0) {
System.out.println(i);
}
}
}
}
Scanner input = new Scanner (System.in);
num1 = input.nextInt();
num2 = input.nextInt();
List<Integer> list = new ArrayList<>();
for(int i=0; i<=Math.min(num1,num2);i++){
if(num1%i==0 && num2%i==0){
list.add(i);
}
}
System.out.println("Divisors:");
for(int a : list){
System.out.println(a); }
if(list.size()<2){
System.out.print("Not Relatively Prime"); }
else { System.out.print("Relatively Prime");}

Creating a loop from Java input

I need to create a loop from user input. For example they have to enter how many times they want to shuffle the cards. And then it will run the loop of the cards being drawn as many times as the user input states. I will apply my entire code.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class stringVariables {
private static boolean isValid;
public static void main (String[]args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner user_input = new Scanner (System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next ();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next ();
String full_name;
full_name = first_name + " " + last_name;
System.out.println( full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
if(num1 + num2 + num3 == 31){
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
}
else
System.out.println("Better Luck Next Time");
//the play again menu. this blocks any input besides 1 or 0
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch=Integer.parseInt(br.readLine());
}
}}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}
what I need to do is loop the user input from
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
And make it replay this loop
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
To make it loop to the desired user input after the completion of their name
Although it's not entirely clear what you're trying to achieve I have tried to modify your code from your original post to make it more readable and function the way you want. Please see my comments in the code below, I tried to prefix all of my comments with "EDIT" so you could easily identify which are mine.
//EDIT: added new import to help with validating user input
import java.util.InputMismatchException;
import java.util.Scanner;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.BufferedReader;
import java.io.IOException;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.InputStreamReader;
import java.util.Random;
//EDIT: changed class name to java standard naming convention using uppercase for first letter.
public class StringVariables {
// EDIT: this variable is not used, I removed it
// private static boolean isValid;
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
// is not inputed
// EDIT: removed this variable as it is no longer used in the code that
// follows.
// boolean testing = false;
// EDIT: Removed this variable in favor of using Scanner.nextInt() in
// the code below
// String pos = "";
// EDIT: Added this variable and initialized to an invalid value so that
// we can loop until a valid value is entered.
int numShuffles = -1;
while (numShuffles < 0) {
// EDIT: This variable is not needed with the new logic
// testing = false;
// EDIT: This is not needed, you already have a Scanner object above
// called user_input
// Scanner sc = new Scanner(System.in);
System.out
.println("How many times do you want the numbers shuffled? ");
try {
// EDIT: modified the lines below to fix infinite loop, forgot
// about certain Scanner behavior so switched back to
// Integer.parseInt
String inputText = user_input.next();
numShuffles = Integer.parseInt(inputText);
} catch (NumberFormatException inputException) {
System.out.print("Please enter a valid number. ");
}
} // EDIT: added closing bracket here
// EDIT: none of the code commented out below is needed when using
// the new code above.
// for(int i=0; i<pos.length();i++)
// {
// if(!Character.isDigit(pos.charAt(i)))
// testing = true;
// }
// if(testing == true)
// {
// System.out.print("Enter only numbers.. ");
// continue;
// }
//
// else
// {
// int key = Integer.parseInt(pos);
//
//
// break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(2000);
System.out
.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// EDIT: rather than repeating the same code over and over just use a
// loop if you want to print 25 blank lines.
for (int i = 0; i < 25; i++)
System.out.println(" ");
// EDIT: see previous comment, removed duplicate code
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
// EDIT: This BufferedReader is not needed with changes to code below
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
Random random = new Random();
// EDIT: removed the following two lines to simplify the looping logic
// int ch = 1;
// while (ch == 1) {
while (true) {
// EDIT: your comment is wrong, you're creating 3 numbers here not 2
// get two random numbers between 7 and 13
// EDIT: no need to create a new Random inside the loop, you can
// re-use a single instance.
// Random r = new Random();
// EDIT: This approach is fine, but I think using the Random class
// is easier to read so I replaced your code with code that uses
// Random
// int num1 = 7 + (int) (Math.random() * (7));
// int num2 = 7 + (int) (Math.random() * (7));
// int num3 = 7 + (int) (Math.random() * (7));
// EDIT: based on your replies it seems like you want to give the user
// several changes for each run of the game and this is what you meant
// by "shuffle". I have implemented that feature below with the for loop.
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
+ (num1 + num2 + num3));
// EDIT: you never use the variable i so I removed this code.
// int i = 0;
// {
// System.out.println(num1 + num2 + num3);
// i++;
// }
if (num1 + num2 + num3 == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
}
}
if (!isWinner)
System.out.println("Better Luck Next Time");
// the play again menu. this blocks any input besides 1 or 0
// EDIT: again, re-use the existing scanner
// Scanner sc = new Scanner(System.in);
// EDIT: There is a much simpler and easier-to-read way to do this
// so I have removed your code and added new code after.
// EDIT: Also this code does not work correctly, it fails to exit
// properly when the user enters a letter.
// while (true) {
// System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
// String input = user_input.next();
// int intInputValue = 0;
// try {
//
// intInputValue = Integer.parseInt(input);
// Integer.parseInt(input);
// break;
// } catch (NumberFormatException ne) {
// System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
//
// ch = Integer.parseInt(br.readLine());
// }
//
// }
// EDIT: here is the new code, see previous comment.
System.out
.println("Do you want to play again? (If you do enter y or yes) ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// EDIT: close the scanner when you're finished with it.
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
Why not just use
while(true) {
try{
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
for(int i = 0; i < pos; i++) {
//do the shuffling
}
I have done some altering in your code and I feel this is what you are looking for. Just copy paste the code and it should work ideally.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner sc = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = sc.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = sc.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
int ch = 1;
while (ch == 1) {
int pos = 0;
System.out.println("How many times do you want the numbers shuffled: ");
while (true) {
sc = new Scanner(System.in);
try {
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
for (int i = 0; i < 100; i++) {
System.out.println(" ");
}
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num1 = 0, num2 = 0, num3 = 0;
boolean isWinner = false;
for (int j = 0; j < pos; j++) {
num1 = 7 + (int) (Math.random() * (7));
num2 = 7 + (int) (Math.random() * (7));
num3 = 7 + (int) (Math.random() * (7));
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
if (num1 + num2 + num3 == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
isWinner = true;
}
}
if(!isWinner){
System.out.println("Better Luck Next Time");
}
//the play again menu. this blocks any input besides 1 or 0
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch = Integer.parseInt(br.readLine());
}
}
}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}

How can i add the random number to my total for java(blackjack)?

This is my code:
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
System.out.println("Card: "+ (random.nextInt(10)));
total = total + (random.nextInt(10));
System.out.println("Total: "+ total);
}
}
}
When I enter n, how can I make it so the program exit, instead of printing out the total again?
Check this out:
public class Assignment2 {
public static void main(String args[]){
int next = 0;
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;
System.out.println("Total: "+ total);
}
if (exit.equals('n'))
system.exit(0);
}
}
Now the program exists after you enter n by calling system.exit(0).
You need to call nextInt just once, so you won't create 2 different random numbers. So I put the first call into a variable next so you could use it as many times as you please without having to call nextInt again.
If you want the program to exit immediately after the user enters n, you will want to put the if statement right after the exit = stdin.next().charAt(0);
If you want to exit the loop, you can break from it. Basically you have to do this(I have written comments to highlight the alterations)-
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
//you need to check here if the user entered 'n'. I have used a break opertion
//to break from the loop and print the total outside the loop. But if you want
//to exit the program altogether, just replace break with exit(0) :)
if(total >= 21 or exit == 'y') {
break;
}
//As Idos correctly pointed out that by calling random.nextInt(10) two
//times you have a very big chance of creating two different random numbers.
//So it makes sense to put the first call into a variable nextNumber.
int nextNumber = random.nextInt(10);
total = total + (nextNumber);
//Now we should again check for total. If it is greater than or equal to 21
//I am again breaking from the loop. Feel free to replace break with exit(0).
if(total >= 21) {
break;
}
System.out.println("Total: "+ total);
}
System.out.println("Your total- "+ total);
}
}

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