end java program when input 'q' - java

i want to end my java program if i input q or Q.
otherwise, the program will continue running, printing the question and asking for input.
will this work?
Scanner sc = new Scanner(System.in);
while(sc.hasNext())
{
System.out.print("Enter departure city <'Q' or 'q' to exit>: ");
String input = sc.next();
if(!(input.equals('q')) || !(input.equals('Q'))){
//system continues
}
else{
System.exit(0);
}
}

String input = "";
while (!input.toUpperCase().equals("Q"))
{
System.out.print("Enter departure city. <'Q' or 'q' to exit>: ");
input = sc.next();
}
Exit after the while loop.

Related

Java program that asks for user's name and prints it - issue with error message

I have a program that asks for the user's name and prints it back out. It can do that part fine, but it currently has the issue of not printing the proper error message when the user leaves the prompt empty and presses "Enter".
The code:
//Get User Input
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
while (sc.hasNext()) {
//User Input Variable
String name = sc.nextLine();
if (name == null || name.trim().isEmpty()) {
//Error for empty input, keep asking for valid input
System.out.print("Please, what is your name?\n");
sc.next();
} else {
//Print name
System.out.println("Hello " + name + "!");
break;
}//End of conditional
}//End of while loop
The current output:
What is your name?
<blank space for input>
<Empty Space where error message should be>
The ideal output:
What is your name?
<blank space>
Please, what is your name?
What's wrong?
The only thing that you need to change is your condition in the while statement.
Please use sc.hasNextLine() insted of sc.hasNext(). Then you will get desired output. Here is the working soltion:
// Get User Input
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
while (sc.hasNextLine()) { // here is the difference in the code
// User Input Variable
String name = sc.nextLine();
if (name == null || name.trim().isEmpty()) {
// Error for empty input, keep asking for valid input
System.out.print("Please, what is your name?\n");
sc.hasNextLine(); // here is the difference in the code
} else {
// Print name
System.out.println("Hello " + name + "!");
break;
} // End of conditional
} // End of while loop
Scanner sc = new Scanner(System.in);
System.out.print("ENTER YOUR USERNAME : ");
String name = sc.nextLine();
while(name.equals("") || name.trim().isEmpty()) {
System.out.print("PLEASE ENTER YOUR USERNAME AGAIN : ");
name = sc.nextLine();
}
System.out.println("WELCOME " + name);

how to terminate an infinite console loop by letting the user press a specific key on the keyboard in java?

hi guys so as you can see it is an infinite loop
and I am asking if I could assign a key on the keyboard that terminates and stops this loop whenever the user presses this key.
NOTE that I am trying to do that in the console, not a UI
do{
//some calculations here
}while(true);
```
Two examples of doing what you want:
First example:
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println("Type X to exit and hit enter");
input = sc.next();
} while(!input.equalsIgnoreCase("x"));
sc.close();
Second example:
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println("Type X to exit and hit enter");
input = sc.next();
if (input.equalsIgnoreCase("x")) {
break;
}
} while(true);
sc.close();
Add your console code to the while-loop; press 'a' or 'A' to exit.
Scanner sc = new Scanner(System.in);
//Type in "a" to end
while (!sc.next().equalsIgnoreCase("a")) {
// console code here
}
System.out.println("Exiting");

how to break or continue a loop from user input

I'm trying to write a code that loops when y is entered and stops when n is entered, this is what I have so far.
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext());{
input.hasNext("y");
}
I have no clue how to continue.
For more readable code you can use a boolean variable and assign it to true according to your input equals to "y" condition
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean stopFlag= false;
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
String userInput =input.next();
if(!userInput.equals("y"))
stopFlag=true;
}while (!stopFlag);
}
You can do this:
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String temp = input.next();
if(temp.equals("y")) {
// if you need to do something do it here
continue; // will go to the next iteration
} else if(temp.equals("n")) {
break; // will exit the loop
}
}
If you are persistent on using do...while then you can try:
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext() && !input.next().equals("n"));

While loop continuing to run despite condition failing

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String sent = "y";
int a = 0;
int b = 0;
System.out.println("Welcome!\nThis program compares two letters in a sentence.");
while(!sent.equalsIgnoreCase("X")) {
System.out.print("Enter a sentence or X to exit: ");
sent = input.next();
System.out.print("Enter the numeric location of the first letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the first letter: ");
}
a = input.nextInt();
System.out.print("Enter the numeric location of the second letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the second letter: ");
}
b = input.nextInt();
System.out.println();
char c = sent.charAt(a);
char d = sent.charAt(b);
if(c==d) {
System.out.println(c+" and "+d+" are identical.\n");
}
else {
System.out.println(c+ " and "+ d + " are unique characters. \n");
}
}
System.out.print("GoodBye!");
}
This loop continues to run even if you input X and I don't know why. Also, when you input a text instead of a number, the error message will like so:
Error! Please enter a number not text!
Enter the numeric location of the first letter: Error! Please enter a number not text!
Enter the numeric location of the first letter:
Only the third sentence will take in user input.
This code sent = input.next()
is not reading a whole sentence. It just reads one word.
Try nextLine() instead.
Also, you should test the exit condition immediately after sent is set.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String sent = "y";
int a = 0;
int b = 0;
System.out.println("Welcome!\nThis program compares two letters in a sentence.");
System.out.print("Enter a sentence or X to exit: ");
sent = input.next();
while(!sent.equalsIgnoreCase("X")) {
//moved accepting input above while condition.This will fix
//X not recognized issue
System.out.print("Enter the numeric location of the first letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the first letter: ");
}
a = input.nextInt();
System.out.print("Enter the numeric location of the second letter: ");
while(!input.hasNextInt()) {
System.out.println("Error! Please enter a number not text!");
input.nextLine();
System.out.print("Enter the numeric location of the second letter: ");
}
b = input.nextInt();
System.out.println();
char c = sent.charAt(a);
char d = sent.charAt(b);
if(c==d) {
System.out.println(c+" and "+d+" are identical.\n");
}
else {
System.out.println(c+ " and "+ d + " are unique characters. \n");
}
}
System.out.print("GoodBye!");
}

Auto skipping input

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): ");
String userIn= in.next();
if(userIn.equals("e")){
System.out.println("Please enter your text that you want to encrypt: ");
String userInput = in.nextLine();
System.out.print("Please enter your shift key(0-25): ");
int userS = in.nextInt();
if(userS < 0 || userS > 25){
System.out.print("Invalid shift key, please enter a valid shift key: ");
userS = in.nextInt();
}
In my above program at following part of code:
System.out.println("Please enter your text that you want to encrypt: ");
String userInput = in.nextLine();
System.out.print("Please enter your shift key(0-25): ");
It is skipping this userInput, it goes over it and asks for the shift key before I enter the text.
This fixed it (tested in Eclipse):
Scanner in = new Scanner(System.in);
System.out.print("Please choose.('e' to encrypt, 'd' to decrypt, 'q' to quit): ");
String userInput = in.nextLine();
if (userInput.equals("e"))
{
System.out.println("Please enter your text that you want to encrypt: ");
userInput = in.nextLine();
System.out.print("Please enter your shift key(0-25): ");
int userS = Integer.parseInt(in.nextLine());
if (userS < 0 || userS > 25)
{
System.out.print("Invalid shift key, please enter a valid shift key: ");
userS = Integer.parseInt(in.nextLine());
}
}
in.close();
I changed your userIn variable to just be userInput, since we didn't need it; your next() call was also changed to nextLine().
I also changed all your nextInt()'s to nextLine()'s. This will help you avoid an Exception later on.
Lastly, always close a Scanner when you are done with it to conserve system resources.
Change:
String userInput = in.nextLine()
to
in.nextLine(); String userInput = in.nextLine();
Simple, change you code to
String userInput = in.next();

Categories

Resources