Why do I need to input my selection twice? - java

Can anyone help me understand why program requires me to input my selection twice before proceeding?
public static void main(String[] args) {
String quit = "quit";
String input = "input";
String print = "print";
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("please enter a command : \n 1) Quit \n 2) Input \n 3) Print \n");
String initialSelection = scan.next();
boolean stringInput = scan.hasNext();
boolean intInput = scan.hasNextInt();
boolean boolinput = scan.hasNextBoolean();
if(initialSelection.equalsIgnoreCase(quit)) {
System.out.println("The program has quit.");
System.exit(0);
}else if(initialSelection.equalsIgnoreCase(print)){
[constructor]
do {
System.out.println("\nplease enter a command : \n 1) Quit \n 2) Input \n 3) Print \n");
initialSelection = scan.nextLine();
if (initialSelection.equalsIgnoreCase(print)) {
new BonusArrayList();
} else if(initialSelection.equalsIgnoreCase(quit)) {
System.out.println("The program has quit.");
System.exit(0);
}
} while (initialSelection.equalsIgnoreCase(print));
}else if(initialSelection.equalsIgnoreCase(input)){
System.out.println("\n Please enter some kind of value (ex: 123, hello, True)");
}
}
I believe it is coming from the nested do-while statement, but I cannot seem to fix that issue. Any tips would be appreciated!

It is because you either need to have
String initialSelection = scan.next();
or
boolean stringInput = scan.hasNext();
boolean intInput = scan.hasNextInt();
boolean boolinput = scan.hasNextBoolean();
If you have both you need to enter twice

Related

How to do multiple condition input validations with different print statements?

I'm a beginner in Java and the problem that I've run into is I'm not sure how to chain input validation together so that the proper response to the user's incorrect input is given. For example, when the user enters something that's not a letter, the program does tell the user that what they've entered is not a letter, but if I then enter more than one letter, the program doesn't print out the correct response. It's based on whichever mistake the user makes first.
I appreciate all feedback.
String input;
final Pattern alphabet = Pattern.compile("^[A-Za-z]$");
Scanner kb = new Scanner(System.in);
System.out.println("Enter a letter of the alphabet: ");
input = kb.nextLine();
while (!alphabet.matcher(input).matches())
{
System.out.println("That's not a letter, try again.");
input = kb.nextLine();
}
while (input.length() > 1 )
{
System.out.println("Please enter only one letter");
input = kb.nextLine();
}
kb.close();
You can try to do likes this: Make it become check condition in if and get the result
final Pattern alphabet = Pattern.compile("^[A-Za-z]$");
Scanner kb = new Scanner(System.in);
public void drive_main() {
System.out.println("Enter a letter of the alphabet: ");
String input = getInput();
while (input == null) {
input = getInput();
}
}
public String getInput() {
String result;
result = kb.nextLine();
if (!alphabet.matcher(result).matches()) {
System.out.println("That's not a letter, try again.");
return null;
}
if (result.length() > 1) {
System.out.println("Please enter only one letter");
return null;
}
return result;
}
OR you can assign you input to a new class package (input, error, and have an error or not) make it more flexible.
final Pattern alphabet = Pattern.compile("^[A-Za-z]$");
Scanner kb = new Scanner(System.in);
public void drive_main() {
System.out.println("Enter a letter of the alphabet: ");
InputSet input = getInput(kb.nextLine());
while (input.isError) {
System.out.println(input.errorMessage);
input = getInput(kb.nextLine());
}
}
public InputSet getInput(String input) {
InputSet result = new InputSet(input, false, "");
if (!alphabet.matcher(result.input).matches()) {
result.errorMessage = "That's not a letter, try again.";
result.isError = true;
}
if (result.input.length() > 1) {
result.errorMessage = "Please enter only one letter";
result.isError = true;
}
return result;
}
private class InputSet {
String input;
boolean isError;
String errorMessage;
InputSet() {
}
InputSet(String input, boolean isError, String errorMessage) {
this.input = input;
this.isError = isError;
this.errorMessage = errorMessage;
}
}
1st is you should not use the while loop to check the condition.
2nd design your program properly loop > verify error.
You should do more good practical and clean code than you can easily find the error. Try to use less loop as possible it will cause more error and the program memory using

parsing Strings in java

The same question was asked before but I the help wasn't sufficient enough for me to get it solved. When I run the program many times, it goes well for a string with comma in between(e.g. Washington,DC ). For a string without comma(e.g. Washington DC) the program is expected to print an error message to the screen and prompt the user to enter the correct input again. Yes, it does for the first run. However, on the second and so run, it fails and my suspect is on the while loop.
Console snapshot:
Enter input string:
Washington DC =>first time entered & printed the following two lines
Error: No comma in string.
Enter input string:
Washington DC => second time, no printouts following i.e failed
Here's my attempt seeking your help.
public class practice {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
String delimit =",";
boolean inputString = false;
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while (!inputString) {
if (userInput.contains(delimit)){
String[] userArray = userInput.split(delimit);
// for(int i=0; i<userArray.length-1; i++){
System.out.println("First word: " + userArray[0]); //space
System.out.println("Second word:" + userArray[1]);
System.out.println();
//}
}
else if (!userInput.contains(delimit)){
System.out.println("Error: No comma in string.");
inputString= true;
}
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while(inputString);
}
}
}
You can easily solve this problem using a simple regex ^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$
So you can check the input using :
boolean check = str.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$");
Then you can use do{}while() loop instead, so your code should look like this :
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
} while (!userInput.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$"));
}
regex demo
Solution 2
...But I can't apply regex at this time and I wish others help me to
finish up the work the way I set it up
In this case you can use do{}while(); like this :
Scanner scnr = new Scanner(System.in);
String userInput;
String delimit = ",";
boolean inputString = false;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
if (userInput.contains(delimit)) {
String[] userArray = userInput.split(delimit);
System.out.println("First word: " + userArray[0]);
System.out.println("Second word:" + userArray[1]);
System.out.println();
} else if (!userInput.contains(delimit)) {
System.out.println("Error: No comma in string.");
inputString = true;
}
} while (inputString);

How to keep the program running if the user entered Y?

Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.
You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));
That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.

Need to close out java with the letter q

I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException

i'm trying to solve an algorithm with java and i find some issue

i'm taring convert this to a Java program :
$ java SpaceTravel
Welcome to the SpaceTravel agency
What do you want do? [h for help]
a
Unknown command. Type h for help
What do you want do? [h for help]
h
h: print this help screen
q: quit the program
What do you want do? [h for help]
q
Bye bye!
Now the problem that my program seem's do an infinite loop at the 2nd do while loop whatever is my choice i tried many algorithm's and steel wont work for me . here is my code :
package gesitionEleve;
import java.util.Scanner;
public class SpaceTravel {
public static void main(String[] args) {
System.out.print("Welcom to the SpaceTravel Agency\n");
int lafin = 0;
while (lafin != 1) {
int taill;
do {
System.out.print("What do you want to do [h for help] : ");
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
taill = test.length();
} while(taill == 0);
char choix = 0;
String test;
if (choix != 'h') {
do {
System.out.print("\nUknown command. Type h for help ");
System.out.print("\nWhat do you want to do : ");
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
} while(choix == 'h');
}
System.out.print("\nh : print this help page ");
System.out.print("\nq : quite the program ");
do {
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
switch(choix) {
case 'h' :
System.out.print("\nh : print this help page ");
System.out.print("\nq : quite the program ");
case 'q' :
System.out.print("Bye bye");
lafin++;
}
} while (choix == 'q' || choix == 'h');
}
}
}
The below program suits your needs:
import java.util.Scanner;
public class SpaceTravel
{
public static void main(String[] args) {
System.out.print("Welcome to the SpaceTravel Agency\n");
String str; //To avoid exception when user enters just an enter
while (true) { //infinite loop
char choix; //for getting a character
System.out.print("What do you want to do [h for help] : ");
Scanner sc = new Scanner(System.in);
str=sc.nextLine(); //get input
if(str.length()!=1) //If no characters or more than one character is entered,
{
System.out.println("Invalid Choice");
continue;
}
choix=str.charAt(0); //get char from str
if(choix=='q') //if char is q,break out of the while loop
break;
if (choix != 'h') { //if char is not h,print invalid input and continue the loop
System.out.println("\nUnknown command. Type h for help ");
continue;
}
System.out.print("\nh : print this help page ");
System.out.print("\nq : quit the program ");
}
}
}
You got the condition of that loop backwards.
If you want to leave the loop when 'h' is entered, it should be :
do {
System.out.print("\nUknown command. Type h for help ");
System.out.print("\nWhat do you want to do : ");
Scanner sc1 = new Scanner(System.in);
test = sc1.nextLine();
choix = test.charAt(0);
} while(choix != 'h');
Currently you are staying in the loop as long as 'h' is entered.
You should also note that test.charAt(0) would throw an exception if the user presses enter without typing any characters.

Categories