Make Java Program Loop until x is entered? - java

I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)

First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))

what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}

try changing it to
while(!numeratorOne.equals("x")){...}

You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}

Related

Boolean method with an incorrect input

I'm a bit stuck on an exercice I have to make and I can't figure out the best way to do it.
I have to make a method that asks a question and expects Y or N. So I thought I would make a boolean method to return true or false, but the problem is that it would also return false if the user puts something other than Y or N. If I'm not mistaken, a boolean method cannot return null.
I'm very new to java and I'm not very far in my course so this problem will probably have a very simple solution. I also tried looking for an answer but didn't seem to find what I was looking for.
This is what I have with the boolean method but i'm not quite happy with it:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
if (reponse.equalsIgnoreCase("Y")) {
return true;
}
else if (reponse.equalsIgnoreCase("N")) {
return false;
}
else {
return false;
}
}
You need only one condition equalsIgnoreCase("Y"), result of its evaluation is basically the return value. All the if-statements in your code are redundant.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
return reponse.equalsIgnoreCase("Y"));
}
Going by your comment you want your program to ask for input again if the input is neither "y" nor "n". You can achieve that behavior by adding an extra loop:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String response = sc.next();
while(!response.equalsIgnoreCase("Y") && !response.equalsIgnoreCase("N")) {
// loop as long as input is neither "y" nor "n" (ignoring case)
System.out.println("Please enter 'y' or 'n'");
reponse = sc.next();
}
// if the loop is done input has to be either "y" or "n" at this point
return reponse.equalsIgnoreCase("y");
}
The problem is at the end you are explicitly telling java to return false when neither a Y or N is entered. I would try putting in another else statement to have the user re-enter the data or just notify them that they have entered the wrong value.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
while(!response.equalsIgnoreCase("Y") ||!response.equalsIgnoreCase("N"){
#Do something here until
the user inputs the correct value.
}
}

Checking length of a String and using do-while in Java

I want to create a program where you enter a string and it checks if the length is 9 or not. If it is, it gives a message that it is okay. If not, it will give a message that is not, and prompt the user to enter the string again. While running it, I always get that is wrong. Where am I going wrong?
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner Secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String Sec = Secnum.nextLine();
do{
if (Sec.length()!= 9);
System.out.println("Wrong lenght Sec,enter again");
Secnum.nextLine();
}while (Sec.length() == 9);
System.out.println("Sec lenght okay");
}
}
You want to request a new value as long as the length is NOT 9.
So your loop should have that as condition. Further your if is incorrect. If in Java needs curly braces else it will effect the next statement only. A statement can be only a semi-colon as well. So your if-statement is completely useless.
To make the code even more compact you can take out the if and swap the do-while loop. That will only run if the condition is true and not once in the beginning no matter the condition.
A code that should work better:
import java.util.*;
public class Sec {
public static void main(String[] args) {
Scanner secnum = new Scanner(System.in);
System.out.println("Give Sec: ");
String sec = secnum.nextLine();
while (sec.length() != 9) {
System.out.println("Wrong lenght Sec,enter again");
secnum.nextLine();
}
System.out.println("Sec lenght okay");
}
}
On a side note: Use lowercase variable names. That is the better code-style :)
You are terminating the if statement.
if (Sec.length()!= 9);
So, the next print always executes irrespective of it being true or not.
Put the logic for failure inside an if block.
if (Sec.length()!= 9) {
// Print failure message
// Other logic
}

Java Input/output MyProgrammingLab 21212

I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input, and an integer variable named total, to accept all the integer values in input, and put them into total. The program recommends a while loop;however, I have no idea what the condition would be since the scanner is tied to (system.in) instead of a file so it is accepting random user input rather than a predefined string. Can anyone offer advice? Here is the current code I've tried to use:
int number = 0;
while (input.hasNext())
{
number = input.nextInt();
total = number;
}
I am getting a message that literally only reads ("compiler error") while not understand what is going on. I understand that hasnext will not work, but even if I remove it I get the same compile error message; furthermore, I'm not sure what while condition to use without the hasNext method.
I tried changing to input.hasNextLine since two people suggest it may be an EOF reached error, but I'm still getting a compiler error.
/*
I am trying to solve a problem in MyProgrammingLab in which I must use a scanner variable named input,
and an integer variable named total, to accept all the integer values in input, and put them into total.
The program recommends a while loop;
*/
private static Scanner input; //Collect user numbers
private static int total = 0; // to display total at end
private static int number = 0; // Variable to hold user number
private static boolean loopCheck = true; // Condition for running
public static void main(String[] args) {
// Main loop
while(loopCheck) {
input = new Scanner(System.in); // Setting up Scanner variable
// Information for user
System.out.println("Enter 0 to finish and display total");
System.out.println("Enter an Integer now: ");
number = input.nextInt(); // This sets the input as a variable (so you can work with the information)
total += number; // total = (total + number); Continually adds up.
// When user inputs 0, changes boolean to false, stops the loop
if(number == 0) {
loopCheck = false;
}
}
//Displays this when 0 is entered and exits loop
System.out.println("Your total is: " + total); // Displays the total here
System.out.println("Program completed");
}

How to ask te user and depending on his response run all the code again?

I'm a newbie in Java. I started these days and I'm practicing the catch and try exception. I have this code below which solve an operation between to numbers and I'd like to know what can I do, if for example I want that the user, once he makes an operation and get his result, that this has the possibility to make another operation. something like comes up a question asking if he wants to realize another problem and the code run again from the beginning.
package justpractice;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner Operation = new Scanner(System.in);
int x=1;
while(x==1){
try{
System.out.println("Insert numerator");
int n1 = Operation.nextInt();
System.out.println("Insert denominator");
int n2=Operation.nextInt();
double division = n1/n2;
System.out.println(division);
x=2;
}
catch(Exception e){
System.out.println("Insert a valid value");
}
}
}
}
You can do, for example, adding an if statement with a
System.out.println("Do you want to recalculate ? (1/0 Yes/No)");
Operation.nextInt();
then if the input is 1, keep x = 1, else do x = 2.
Try this code amendment;
package justpractice;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner Operation = new Scanner(System.in);
//better practice
while(true){
try{
System.out.println("Insert numerator");
int n1 = Operation.nextInt();
System.out.println("Insert denominator");
int n2=Operation.nextInt();
double division = n1/n2;
System.out.println(division);
System.out.println("Continue? (y/n)");
String response = Operation.nextLine();
if (response.equals("n")){
break;
}
}
catch(Exception e){
System.out.println("Insert a valid value");
}
}
}
}
To allow your user to calculate division again, you could use a do-while loop. With this loop you can execute the code inside once, ask the user if they would like to calculate again, and repeat the code if they do.
An outline of your code with the loop would something like this:
...
boolean again = true;
do { //Main loop
try {
... //Your division code
... //Put code to ask the user if they want to calculate again here
} catch(Exception e) {
...
}
} while(again == true); //Repeat if the user wants to continue
To get input on if the user wants to calculate again, I recommend using another do-while loop with your Scanner. This loop will allow you to repeat the code when the answer is invalid. In this case, when it's not "y" or "n".
String input;
do {
System.out.println("Would you like to continue? (y/n)");
input = operation.next();
} while(!input.equalsIgnoreCase("y") && !input.equalsIgnoreCase("n"));
After you have got the user's input, you still need to terminate the loop if they said "n". To do this you could use an if statement.
if(input.equalsIgnoreCase("n")) {
again = false; //Terminate the main loop
operation.close(); //Prevent any resource leaks with your Scanner
}
There is no need to check if the user input "y" as again is set to true by default.
Side Note: Variables should always be camelCase. Look at the Java Naming Conventions to learn more about naming things in Java.
EDIT:
The reason the console is repeatedly logging that you entered a non-number even though you entered it once, I'm not exactly sure. I think it's because the call to nextInt() never finishes because of the InputMismatchException being thrown, causing the next call to nextInt() (After the do-while repeats) to think that the letter/symbol you just entered is the one you want to process, repeating the exception over and over again.
To solve this, add this line into your catch block:
if(operation.hasNext()) operation.next();
This will call next() and complete the process of marking the letter/symbol you just entered as already processed, then repeat the do-while loop as normal.

How to insist that a users input is an int?

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}

Categories