Loop sequence stops - java

I put the code in a do-while loop. It asks the user which menu option they want and it computes the equation for them. The code is supposed to keep on going until the user hits 4 which is the quit option, but it stops after one sequence. I dont know what I need to change or add so it keeps on going.
import java.util.Scanner;
import java.text.DecimalFormat;
class Lab5
{
public static void main(String[] args) //header of the main method
{
Scanner in = new Scanner(System.in);
int choice;
int rem = 0;
int num;
do
{
//user prompt
System.out.print("Choose from the following menu\n1) Calculate the sum of integers 1 to m\n2) Factorial of a number\n3) Repeat the first number\n4) Quit\n:");
choice = in.nextInt();
switch(choice)
{
case 1:
int m, sum =0;
int i = 1;
System.out.print("Enter the number:");
m = in.nextInt();
while (i <= m)
{
sum=sum+i;
i++;
}
System.out.print("The sum of:" + m + ' ' + "is" + ' ' + sum);
break;
case 2:
int number, fact =1;
System.out.print("Enter the number:");
number = in.nextInt();
i=1;
for (int factor = 2; factor <= number; factor++)
{
fact = fact*factor;
}
System.out.print("The Factorial of +:" + number + ' ' + "is" + ' ' + fact);
break;
case 3:
System.out.print("Enter the number:");
num = in.nextInt();
while(num!=0)
{
rem = num%10;
num = num/10;
}
System.out.print("The leftmost digit is:" + rem);
break;
default:
break;
}
} while (choice == '4');
System.out.print(" ");
}
}

You wrote this as do ... while ( choice == '4' ), which means it will only continue if the user enters a 4.
Sounds like you want choice != '4'.

Related

Reset a for loop inside a switch statement

The code that I have runs, but when I do the do-while loop, the for loop does not reset back to 1 when the user chooses Yes to rerun the program. I hope I am making myself clear.
int choice;
int num;
int i;
String input;
int b = 1;
switch (choice) {
case 1:
do {
System.out.println("The starting number is 1.");
//Input
System.out.print("Enter a value: ");
num = sc.nextInt();
for (i = 1; i <= num; i++) {
b = b * i;
//Output
System.out.printf("%d! = %d\n", i, b);
}
System.out.print(
"Run the program again? (Y for Yes, N for No): ");
input = sc.next();
} while (input.equalsIgnoreCase("Y"));
if (input.equalsIgnoreCase("N")) {
System.out.println(
"Have a great day!");
System.exit(0);
}
break;
}
I tried a while loop instead of the for loop and I was not getting the results at all. I am new to Java so I am still learning.
I added a break at the end of the for loop, but that ends the loop only after 1 increment.
You don't need a switch expression. Also, declare the variables in the narrowest scope. In this case, except for sc, they should be declared in the do/while loop, or in the case of b, in the for loop.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("The starting number is 1.\n");
System.out.print("Enter a value: ");
// Input
int num = sc.nextInt();
for (int i = 1, b = 1; i <= num; i++) {
b = b * i;
// Output
System.out.printf("%d! = %d\n", i, b);
}
System.out.print(
"Run the program again? (Y for Yes, N for No): ");
String input = sc.next();
if (input.equalsIgnoreCase("N")) {
System.out.println(
"Have a great day!");
sc.close();
System.exit(0);
}
} while (true);
}

Decrement by a certain amount on java

i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.

How can I ask the user to re-enter their choice?

I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
You will need to use a loop, which basically, well, loops around your code until a certain condition is met.
A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
Try this, i just include the while loop in your code it will work fine.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = askInput(input);
while(number<10 || number>999) {
System.out.println("Sorry Try again !");
number = askInput(input);
}
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
private static int askInput(Scanner input) {
int number = input.nextInt();
return number;
}

ArrayList If Loop not working properly: JAVA

I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire code.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
//full name printed together
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
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// 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(3000);
System.out
.println(" You will be given " + numShuffles + " hand(s) 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);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
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));
numberStore.add(num1 + num2 + num3);
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
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));
numberStore.add(num1 + num2 + num3);
int lastNumber = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
System.out.println("Better Luck Next Time");
}
}
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// random number generator
Random random = new Random();
while (true) {
// the shuffle 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);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
// if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
// full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
return full_name;
}
private static int initGame(Scanner user_input){
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
// this is the buffer that resets if the user types a letter
// instead of a number, or any other character
user_input.next();
}
}
// 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(3000);
System.out.println(" You will be given " + numShuffles + " hand(s) 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);
return numShuffles;
}

if and else statements not working java

Hi I am trying to take in an integer between 1 and 10.
If the user does not do so would like the program to run again.
I believe that I need to use an else if statement that calls on my function but I do not know how to call functions in java.
Here is my code so far:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
if (num1 >= 1 && num1 <= 10); {
System.out.println("Input = " + num1);
}
else if {
???
}
}
}
if-else always work.
You made a mistake in the if statement.
there is no ; for an if
if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}
What happens if I put a semicolon at the end of an if statement?.
How do I ask the user again if the input is not in between 1 and 10?
Loop until you get what you want :)
Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
num = sc.nextInt();
if(num > 0 && num < 11)
break;
System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);
Since you are expecting a number between 1 to 10, but you don't know how many numbers you will get until you get a valid number, I'd suggest to use a while loop, like so:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
while (num1 < 1 || num1 > 10) {
System.out.print("Invalid number, enter another one: ");
num1 = in.nextInt();
}
System.out.println("Input = " + num1);
}
}

Categories