How to loop this simple program? - java

How do i loop this WHOLE program?
public class Experiments {
public static void main(String[] args) {
int n;
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
}
}
When it prints out the result:
The result is 14.
I want it to say something like:
Had fun? Lets do it again.
Please enter a number:
or
Had fun? Want do it again. Press y/n.
Please enter a number:

You have to do something like this:
Scanner s = new Scanner(System.in);
char c;
do {
your_code
c = s.next().charAt(0);
} while(c == 'y');
And thanks to this your program will ask you everytime if you want to continue and when you enter 'y' then it will loop again. Otherwise it will exit from the loop.

To combine your code with the example from wawek:
public class Experiments {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
do {
play();
System.out.println("Again ( press y ) else press Anykey");
c = s.next().charAt(0);
} while(c == 'y');
}
public static play(){
int n;
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
}
}

public class Experiments {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char c;
int n;
do{
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
System.out.println("Had fun? press y do it again n to exit");
c = s.next().charAt(0);
} while(c == 'y');
}
credit goes to #wawek

Just read user next line character for yes and then run the whole sequence as shwon below.
public class Experiments {
public static void main(String[] args) {
int n;
while(againFlag=='y'){
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
System.out.println("Had fun. Want do it again?(Press 'y')");
char againFlag = TextIO.getlnChar();
}
}

You can use recursive. Sample like this:
public class Experiments {
public static void main(String[] args) {
guess();
}
public static void guess() {
int n;
System.out.print("Please enter a number:");
n = TextIO.getlnInt();
while (n<3) {
System.out.print("Please enter another number:");
n = TextIO.getlnInt();
}
while (n<=5) {
System.out.println("Number entered should be more than 5.");
System.out.println("Please re-enter:");
n=TextIO.getlnInt();
}
if (n%2==0) {
n=n*2+1;
}
else {
n=n*2;
}
System.out.println("The result is "+n +".");
System.out.println("Had fun? Lets do it again.");
guess();
}
}

Related

NoSuchElementException error for ATM Machine app (Modified)

I am currently learning Java and I am trying to retain the information I learned by building a ATM machine app (I plan on adding more to it in the future).
My current issue is I would like to ask a user 'What would you like to do' repeatedly until a valid input is provided(current valid inputs are 'Withdraw' and 'Deposit').
I have a loop that will repeatedly ask the user 'Please select a valid choice' if the input is not valid. If the input is valid it will execute only once, ask 'What would you like to do', and then display a NoSuchElementException. Not sure how to fix this.
Here is my code:
App.java
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("What woul you like to do?");
String response = scanner.next().toLowerCase();
Transactions newTransaction = new Transactions();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
} else if (response.equals("deposit")) {
newTransaction.Deposit();
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}
Transactions.java
import java.util.Scanner;
public class Transactions {
private int currentBalance = 100;
public void Withdrawal() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to withdraw?");
int withdrawAmount = scanner.nextInt();
if (withdrawAmount > 0) {
if (currentBalance > 0) {
currentBalance -= withdrawAmount;
System.out.println("Amount withdrawn: $" + withdrawAmount);
System.out.println("Current Balance: $" + Balance());
if (currentBalance < 0) {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println(
"You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee");
}
} else {
System.out.println("Can't remove 0 from account");
}
scanner.close();
}
public void Deposit() {
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to deposit?");
int depositAmount = scanner.nextInt();
if (depositAmount > 0) {
currentBalance += depositAmount;
Balance();
}
System.out.println("Amount deposited: $" + depositAmount);
System.out.println("Current Balance: $" + Balance());
scanner.close();
}
public int Balance() {
return currentBalance;
}
}
Error Message
NoSuchElementException
You can use a sentinel. A sentinel is a value entered that will end the iteration.
//incomplete code showing logic
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice");
choice = input.nextInt();
while(choice != -1){ //-1 is the sentinel, can be value you choose
//Some logic you want to do
System.out.println("Enter choice or -1 to end");
choice = input.NextInt(); //notice we input choice again here
}
Like has been said you should learn about loops. There are two types while-loop and for-loop. In this case you should youse the while-loop.
The implementation of your problem could be this.
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("What woul you like to do?");
String response;
Transactions newTransaction = new Transactions();
while (true) {
response = scanner.next().toLowerCase();
if (response.equals("withdraw")) {
newTransaction.Withdrawal();
break;
} else if (response.equals("deposit")) {
newTransaction.Deposit();
break;
} else {
System.out.println("Please select a valid choice");
}
}
scanner.close();
}
}

How can I store the scanner input integers in Java so I can print the sum of a list of input integer numbers?

I'm doing the University of Helsinki's Java MOOC and there is an exercise that asks me to create a program that lets you input as much numbers as you want, but when you input a '0' it prints the sum of all the previously input numbers and ends the program. I can't figure out how to 'store' the input numbers for calculating the sum of them when you input a '0'. The program works but inputting '0' prints '0'. This is how my code looks:
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number.");
while (true) {
try {
int number = Integer.parseInt(scanner.nextLine());
System.out.println("Input another number.");
if (number == 0) {
System.out.println(number + number);
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
How can I calculate the sum of all the input numbers?
You can create a counter and make smth like this, you don't need to save all numbers:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
System.out.println("Input a number.");
while (true) {
try {
int number = Integer.parseInt(scanner.nextLine());
sum += number;
System.out.println("Input another number.");
if (number == 0) {
System.out.println(sum);
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
In line with my comment above:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int number = -1;
while (number != 0) {
try {
System.out.print("Input a number (0 to quit): ");
number = Integer.parseInt(scanner.nextLine());
sum += number;
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
System.out.println("Total:" + sum);
}

a positive and negative checker with odd and even checker

How can I check if an input number is negative or positive, and if it is positive it will check again if it is odd or even, and if it's negative an error message will appear and ask again the user if he/she wants to check another number?
import java.util.Scanner;
public class OddEvenChecker{
public static void main(String[] args){
int integer=0;
Scanner sc = new Scanner(System.in);
while (true) {
if (integer>=0) {
System.out.print("Enter a positive Integer: ");//gets the user input
integer = sc.nextInt();
}
if (integer<0) { // checks if the entered number is a positive integer
System.out.println("Error");
System.out.print("Do you Want to Continue? y for Yes, n for No: ");
String choices = sc.nextLine();
} else if(integer>0) {
if (integer%2==0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}
}
}
public class OddEvenChecker {
public static void main(String[] args) {
int integer = 0;
String flag = "y";
Scanner sc = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
do {
System.out.print("Enter a positive Integer: ");//gets the user input
integer = intScanner.nextInt();
if(integer>0) {
if(integer%2==0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
} else {
System.out.println("This is negative number. Try again.");
}
System.out.print("Do you want to Continue? y for Yes, n for No: ");
flag = sc.nextLine();
} while(!(flag.equals("n") || flag.equals("no")));
}
}
What do you think about this approach? Does it meet requirements?
do{
choices = sc.nextLine();
if(choices.equals("n") || choices.equals("no"){
return;
}
else if(choices.equals("y") || choices.equals("yes"){
break;
} else {
System.out.println("invalid key");
}
} while(!choices.equals("n") || (!choices.equals("no") || (!choices.equals("y") || (!choices.equals("yes"));
enter code here
public class OddEvenChecker{
public static void main(String[] args){
int integer=0;
Scanner sc = new Scanner(System.in);
while (true) {
if (integer>=0) {
System.out.print("Enter a positive Integer: ");
integer = sc.nextInt();
if(integer%2==0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
if (integer<0) {
System.out.println("Error");
System.out.print("Do you Want to Continue? y for Yes, n for No: ");
String choices = sc.nextLine();
}
}
}
}//Maybe this is the best and easiest way to do this.

I would like put a optional "wrong number. Try again" when is

I have just started learn java codes, that is why might I have a simple question that is not simple for me.
I would like put a optional "wrong number. Try again" when is entered different number than secretNum. May you guys help me out on this code?
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if(sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " + userName + ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done\n");
System.out.println("Are you ready for the next step?\n");
}
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
System.out.println("Enter Yes or No");
while(!sc.next().equals("yes")&& !sc.next().equals("no"));{
System.out.print("Yes");
}
do {
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt ();
}
}while(secretNum2 != guess);{
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}
}
````````
You don't need do{} while() for the checks you want to do here, just while(){} loops would be enough.
Please try this code instead:
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if (sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " + userName + ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum != guess) {
System.out.println("Please try again\n");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Well done\n");
System.out.println("Are you ready for the next step?\n");
System.out.println("Enter Yes or No");
while (!sc.next().equals("yes") && !sc.next().equals("no"))
{
System.out.print("Yes");
}
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum2 != guess) {
System.out.println("Please try again\n");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

Categories