Java how to continue current loop when condition is false - java

I am having an issue whereby whenever input validation is incorrect it breaks out of my current loop and continues with the next method can anyone help me so that when condition is false it re-asks for the same input until it meets the condition. Here's my source code for my method class
public class Student {
public int gradePt;
public int i;
public int credSum = 0;
public double gradeCredSum = 0;
public double gpa;
String [] moduleName;
String [] moduleGrade;
int [] moduleCred ;
Module[] modules;
public void createModules(){
getModuleNo();
modules = new Module[i];
moduleName = new String[i];
moduleGrade = new String[i];
moduleCred = new int[i];
getModule();
getGrade();
getCred();
for (int j = 0; j < modules.length; j++) {
modules[j] = new Module(moduleName[j],moduleCred[j],moduleGrade[j]);
}
}
public void getModuleNo(){
do{
String input = JOptionPane.showInputDialog(null,
"How many modules did you take?","Input");
int a = Integer.parseInt(input);
if (a<1 || a>8){
JOptionPane.showMessageDialog(null,
"Invalid input please enter a number greater than 0",
"Error",JOptionPane.ERROR_MESSAGE);
break;
} i = a;
}while(i<1 || i>8);
}
public void getModule(){
for (int i=0;i<moduleName.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter the name of module #"+(i+1));
moduleName[i] = input;
if (input == ""){
JOptionPane.showMessageDialog(null,
"Invalid input, module name cannot be blank","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
public void getGrade(){
for (int i=0;i<moduleGrade.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter grade (A,B,C,D,F) for module #"+(i+1));
moduleGrade[i] = input;
if (!"A".equals(input) && !"B".equals(input) && !"C".equals(input) && !"D".equals(input) &&
!"F".equals(input) && !"a".equals(input) && !"b".equals(input) && input!="c" &&
!"d".equals(input) && !"f".equals(input)){
JOptionPane.showMessageDialog(null,
"Invalid input!"+"\n"+"Please enter A,B,C,D or F","Error",JOptionPane.ERROR_MESSAGE);
break;
}
moduleGrade[i] = input;
}
}
public void getCred(){
for (int i=0;i<moduleCred.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter credit units for module #"+(i+1));
moduleCred[i] = Integer.parseInt(input);
if (moduleCred[i]<1 || moduleCred[i]>8){
JOptionPane.showMessageDialog(null,
"Invalid input!"+"\n"+"Please enter a number form 1 to 8","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
}

This is a common process. You keep asking for input, checking it each time until the input is valid.
Pseudocode:
repeat
display("Please enter your input: ")
input <- getInput()
until (isValid(input))

There are many loops in your program asking for input. so here is some code for your problem
boolean inputOk=false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
do{
// ask for input
System.out.println("Enter the value");
// capture input
String input = reader.readLine();
// evaluate input
if(input.equals("ok"))
inputOk = true; // set flag if input is ok
}while(!inputOk); // if flag is ok then exit loop

I count four getter methods where you use a JOptionPane to gather user input. In the code snippet below, I have refactored getGrade() such that it continues to prompt the user for input, for a given module grade, until valid input is received.
While the fix for your three other methods is not given here, you can try following a similar pattern.
public void getGrade() {
String invalidInputMsg = "Invalid input!" + "\n" + "Please enter A,B,C,D or F";
for (int i=0; i < moduleGrade.length; i++) {
do {
String enterGradeMsg = "Enter grade (A,B,C,D,F) for module #" + (i+1)";
String input = JOptionPane.showInputDialog(null, enterGradeMsg);
if (input.length() == 1 &&
"ABCDF".indexOf(input.toUpperCase().charAt(0)) != -1) {
moduleGrade[i] = input;
break;
}
else {
JOptionPane.showMessageDialog(null, invalidInputMsg, "Error",
JOptionPane.ERROR_MESSAGE);
}
} while(true);
}
}
If the input be valid, then break will end the do loop, and the next value of i will be used in the for loop, should it be available. If the input be invalid, then the do loop will continue and prompt the user again for input.

Related

i want to display every number entered in my while loop.so how can i do this

must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}

User validation input under forloop

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String regex = "[a-zA-Z ]+$";
String regex1 = "\\d[0-9]|[1-9]";
String regex2 = "^[a-zA-Z0-9 ]+$";
String petName;
StringBuilder output = new StringBuilder();
do {
System.out.print("\nHow Many Pet do you have? Give from 1-3:");
petName = input.nextLine();
if (petName.isEmpty()) {
System.out.println("Number field should not be Empty.");
} else if (!petName.matches(regex1)) {
System.out.println("Please Enter A Valid Number!");
}
} while (!petName.matches(regex1));
do {
Integer.parseInt(petName);
String[] pets = new String[Integer.parseInt(petName)];
System.out.print("\nList Down All Your Pet Names:\n");
for (int i = 0; i < pets.length; i++) {
System.out.print("\nPET" + (i + 1) + ":");
pets[i] = input.nextLine();
if (pets[i].isEmpty()) {
System.out.print("String field should not be Empty.");
} else if (!pets[i].matches(regex)) {
System.out.print("Please input a valid String.");
}
}
output.append("\nThese Are The List Of The Pets You Have:");
for (int i = 0; i < pets.length; i++) {
output.append("\nPET:").append(i + 1).append(" ").append(pets);
}
} while (!petName.matches(regex));
System.out.println(output);
}
I'm having a little problem with the above codes.
What I want is if I input an integer then it will prompt me this message "Please input a valid String" or if I didn't type anything in the field then it will prompt me this another message "String field should not be Empty". But what happen is even if I type a string value in the field then it's still prompting the message "Please input a valid String" and the loop is still keep doing the same over and over again every time I press enter.
You have some issues with your second while loop. First of all, your loop condition is checking petName, which isn't changed after leaving the first while loop. Second, the for loop seems to be nested incorrectly. Since you want to loop for a valid input of each pet name, you should put the second while loop in the for loop and not the other way around.
It's probably easier to see with the following modified code. Also note that calling append(pets) outputs the toString result of the pets array and not the individual pet name. For this you should use append(pets[i]).
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String regex = "[a-zA-Z ]+$";
String regex1 = "\\d[0-9]|[1-9]";
String regex2 = "^[a-zA-Z0-9 ]+$";
String petName;
StringBuilder output = new StringBuilder();
do
{
System.out.print("\nHow Many Pet do you have? Give from 1-3:");
petName = input.nextLine();
if (petName.isEmpty())
{
System.out.println("Number field should not be Empty.");
}
else if (!petName.matches(regex1))
{
System.out.println("Please Enter A Valid Number!");
}
} while (!petName.matches(regex1));
String[] pets = new String[Integer.parseInt(petName)];
System.out.print("\nList Down All Your Pet Names:\n");
for (int i = 0; i < pets.length; i++)
{
do
{
System.out.print("\nPET" + (i + 1) + ":");
pets[i] = input.nextLine();
if (pets[i].isEmpty())
{
System.out.print("String field should not be Empty.");
}
else if (!pets[i].matches(regex))
{
System.out.print("Please input a valid String.");
}
} while (!pets[i].matches(regex));
}
output.append("\nThese Are The List Of The Pets You Have:");
for (int i = 0; i < pets.length; i++)
{
output.append("\nPET:").append(i + 1).append(" ").append(pets[i]);
}
System.out.println(output);
}

clearing a java string after loop

I am new to Java and am creating a project for class that basically asks the user to input a string, and then tests the string and prints whether or not it is a palindrome (the same forwards as backwards... i.e. mom or dad or racecar)
I have gotten the code to work, however i have a loop setup to rerun the program or quit at the end. My problem is that when you rerun the program and enter another String input then it's adding it to the original string.
How can I reset or delete the String input each time so that it starts fresh?
Thank you for any help! Also please note, there may be better or faster ways to accomplish what I have done here but my knowledge of java is limited and I am just getting started, so I have used the knowledge that I have thus far learned. Thanks!!
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Ok, figured it out thanks to your guys' help... also rewrote the code so that you can just keep entering new strings or type q to quit instead of the redo question at the end. Hopefully this is cleaner!
import java.util.Scanner;
public class Palindrome_Test {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
int length; //length of word entered by user
boolean redo = true; // boolean to rerun program
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please enter a string, or type Q to quit: ");
input = scan.nextLine();
if (input.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
redo = false;
} else {
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
reverse = "";
}
} while (redo);
} //end main
} //end class
At the end of your while loop add reverse = "";
You'll notice that I moved the following -
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
Inside of the first loop. Although you could simply reset both variables at the end of the loop...
input = "";
reverse = "";
There is no need to (Although, they both work!). By dealing with the scope of the variable inside of the loop, it will essentially "refresh" each time the loop executes.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// String input = ""; // Word entered by user
// String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class

Java Scanner Lookahead

Is there any way to implement Scanner.hasNextInt() so that it can check not only the i+1 token but the i+2 token? I am looking for a way to check if both inputs are numbers without printing the same error message twice.
Input should be in the form
1 2
and I am trying to alert the user if input is of the form
1 a, a 1, a a, aa aa, 1a 1, etc...
What I wish it would look like: (does not work this way)
int pile1, pile2;
// the second call to reader.hasNextInt() would be verifying pile2 to be int
if (reader.hasNextInt() && reader.hasNextInt())
{
pile1 = reader.nextInt();
pile2 = reader.nextInt();
}
else
{
System.out.println("Your input is malformed. Try again");
}
What I currently have:
int pile1, pile2;
if (reader.hasNextInt())
pile1 = reader.nextInt();
else
{
System.out.println("Your input is malformed. Try again");
return;
}
if (reader.hasNextInt())
pile2 = reader.nextInt();
else
{
System.out.println("Your input is malformed. Try again");
return;
}
You can use
hasNext(String pattern) this method returns true if the next token matches the pattern constructed from the specified string.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
List<Integer> data = new ArrayList<Integer>();
System.out.println("input count of numbers to inputed:\t");
int limit = 0;
if (reader.hasNext("\\d+")) {
reader.nextInt();
} else {
System.out.println("wrong input");
return;
}
System.out.println("please input data:\t");
for (int i = 0; i < limit; i++) {
if (reader.hasNext("\\d+")) {
data.add(reader.nextInt());
} else {
System.out.println("Your input is malformed. Try again");
break;
}
}
reader.close();
}
assumption:Since you need to stop scanning ,one must have predefined limit set or special exit condition from loop.

Validating user input with a loop

Alrighty, I'm currently trying to make a program that takes input, in the form of a email address, from the user and checks to see if it has a '#' in it. I want to use a loop to steps through the whole string that the user entered, and checks each character for the '#'. I'm a little lost as to how to get started.
What I did, was use a for loop to iterate through the whole string that the user entered. Then I used a do/while loop to execute a certain line of code until the user entered a valid email. However, it seems to always be valid no matter if it has a '#' or not. I also want to check if it only contains 1 '#' in it. I'm a little lost as you can see, but any help would be appreciated!
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
System.out.print("Enter an email address ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
valid c = new valid(input);
}
}
class valid
{
String scan2;
char amper = '#';
int i;
valid(String scan1)
{
scan2 = scan1;
for (i = scan2.length() - 1 ; i <= 0; i--)
do
{
System.out.print("That input is invalid");
} while(scan2.indexOf(i) != amper);
System.out.println("That input is valid");
}
}
Since you have to use a loop, I would recommend charAt. It gives you the character at a given index in a string:
boolean found = false;
//where string is the input that you are scanning to find an email address
for (int i = 0; i < string.length; i++){
if (string.charAt(i) == '#'){
found = true;
break;
}
}
if (found){
System.out.println("Found the # character!");
}
Hope it helps you
Loop the each character in the loop.
Check for '#' character
String email = "test#gmal.com";
boolean valid = false;
for (int i=0;i<=email.length();i++) {
if (email.charAt(i)== '#') {
valid = true;
break;
}
}
if (valid) {
System.out.println("This is valid email Id");
} else {
System.out.println("This is an Invalid email Id");
}
Others have already made some helpful comments, but here a few other things I have noticed:
Did you mean to have no "{} after the for statement? Not having that { } can change the program.
In the for statement, did you want it to be i <= 0 or i >= 0? If i starts out being the length of the input string and the test in the for statement is i <= 0, it will never be true unless the input is zero length.
Why do you have a scan1 and a scan2 String?
You may want to consider removing your search logic from the constructor.
I recommend using charAt() method in this case. Here is my code.
import java.util.Scanner;
public class EmailAddr {
private String emailAddress;
public EmailAddr(String emailAddress){
this.emailAddress = emailAddress;
}
public boolean isValid(){
boolean isValid = false;
int nAtSign = 0;
for (int i = 0; i < emailAddress.length(); i++){
if(emailAddress.charAt(i) == '#')
nAtSign++;
}
if(nAtSign == 1)
isValid = true;
return isValid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your email address: ");
EmailAddr emailTest = new EmailAddr(sc.nextLine());
sc.close();
if(emailTest.isValid()){
System.out.println("The email address is VALID!");
} else {
System.out.println("The email address is INVALID!");
}
}
}
Javadoc concerning indexOf:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your E-Mail:");
String line;
do {
line = sc.nextLine();
}
while(line.indexOf('#') == -1);
Why dont you try with regular expressions ??
public class EmailValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean flag;
do{
String pattern="[a-zA-Z]*#[a-zA-Z.]*";
//if u need to think of much better email validation..
//String pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
System.out.println("Enter your Email here :");
flag=scanner.next().matches(pattern);
if(!flag){
System.out.println("Not a valid Email.");
}else{
System.out.println("Valid Email.");
}
}while(!flag);
}
You can use this code as class valid.
class valid {
String scan2;
char amper = '#';
boolean isFound = false;
valid(String scan1) {
scan2 = scan1;
for (int i = 0; i < scan2.length(); i++) {
if (scan2.charAt(i) == amper) {
isFound = true;
}
}
if(isFound) {
System.out.println("Seems like valid email.");
}
}
}
This code based on your class valid and continue some critical errors. As example : "What happen if user input contains more # characters.

Categories

Resources