While loop continuing to run despite condition failing - java

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!");
}

Related

Trouble setting a Parameter

Im confused as to how I allow only numbers 1-4? Im not sure if there is a term for this, i think its parameter
THE CODE IM QUESTIONING IS THE 3RD TO LAST LINE
private void validatePositiveNumber() {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number < 4);
System.out.printf("You have entered a positive number %d.\n", number);
}
Use while (number > 4 || number < 1); This disallows anything outside of the range.
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number > 4 || number < 1);
System.out.printf("You have entered a positive number %d.\n", number);

Scanner doesnt read input in else statement

Im trying to ask the user for two numbers. I want to check if those inputs are in fact numbers but the code I have so far does not let me enter a second value if the first input is a string.
So the scanner does not read anything the else statement.
How could I make it work?
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fname = console.nextLine();
System.out.print("Please enter your last name: ");
String lname = console.nextLine();
System.out.print("Please enter your first number: ");
if (console.hasNextInt()) {
int number1 = console.nextInt();
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
}
} else
System.out.print("Please enter your second number: ");
if (console.hasNextInt()) {
int number2 = console.nextInt();
// this part does not work
}
}
}
You just need to add console.nextLine(); after your else statement, because the Scanner.hasNextInt method does not move cursor past your previous input (if it is a string).

How to restrict amount of characters a user can enter?

For my program below, I want it so that the user must enter a word 2 or more characters long, but I do not know how to make that restriction.
This is a palindrome program, and it is used to test whether the word is a palindrome or not. It lets me enter a word of any length but I want to restrict to 2 or more, and if they enter only a one character word, a message should display "Wrong word".
import java.util.*;
class PalindromeTesterSamJiang1 {
public static void main(String [] arg) {
int x=0;
Scanner in=new Scanner(System.in);
System.out.printf("Menu: Please select an option \n"
+ "1)Palindrome Tester\n"
+ "0)Exit program \n");
x=in.nextInt();
switch (x){
case 1:
lol test=new lol();
test.palindromeTester("");
test.displayInfo();
break;
default:
System.out.println("Goodbye");
break;
}
}
}
class lol {
String original, reverse = "";
public String palindromeTester(String reference) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word to Test: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
return original;
}
public void displayInfo() {
if (original.equals(reverse))
System.out.println("RESULT: A PALINDROME");
else
System.out.println("RESULT: NOT A PALINDROME");
String[] arguments = new String[] {"123"};
PalindromeTesterSamJiang1.main(arguments);
}
}
You can read the input in a loop,
print an error if the input is too short,
break out when you get a valid input, for example:
while (true) {
System.out.println("Enter a word to Test: ");
original = in.nextLine();
if (original.length() > 2) {
break;
}
System.out.println("Too short. Word must be at least 2 characters");
}
System.out.println("Enter a word to Test: ");
original = in.nextLine();
String[] array = original.split(" ");
if(array.length < 2)
System.out.print("Enter atleast 2 sentence");

Do While Loop Skipping User Input

I want it to loop again when the user enters "Y" or "y" and quit when they enter "N" or "n". The quitting option works, however, when they enter Y/y, it shows the first system out, but does not let the user pick which operation they wish to do. Instead the option to continue pops up again and inhibits the user from making any choice.
Here is the code:
import java.util.Scanner;
public class Calc2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double numOne, numTwo, ans;
String option;
do {
System.out.println(
"For addition press '1', for subtraction press '2', for division press '3', for multiplication press '4'");
String choice = input.nextLine();
if (choice.contains("1")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne + numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
else if (choice.contains("2")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne - numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("4")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne * numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
} else if (choice.contains("3")) {
System.out.println("Enter the first number : ");
numOne = input.nextDouble();
System.out.println("Enter the second number : ");
numTwo = input.nextDouble();
ans = numOne / numTwo;
System.out.println("The answer is: " + ans + " ya bish.");
}
System.out.println("Press 'Y' to continue or 'N' to quit.");
option = input.next();
} while (option.equals("Y") || option.equals("y"));
if (option.equals("N") || option.equals("n")) {
System.out.println("Thank you. ");
}
}
}
If anyone can help me, it'd be greatly appreciated. Thanks!
Please change below line in your code
String choice = input.nextLine();
from this code
String choice = input.next();
There trouble you see here is the use of nextLine after nextDouble. Check here [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
Your problem appears to be at the beginning of your do-while loop as such:
System.out.println(
"For addition press '1', for subtraction press '2', " +
"for division press '3', for multiplication press '4'");
String choice = input.nextLine();
This is the only place where you use nextLine method (rahter than next or nextDouble and so on). This means that after you've read the option argument at the end of the iteration:
option = input.next();
there's still a new line character that hasn't been read by the scanner. When you do nextLine() in the next iteration it reads the new line character before the user has any chance to input something).
Either change that first line to input.next() as well, or make sure every time you read a value, you clear the new line character (for instance by reading nextLine and then casting the value - this would also allow you to do input validations).

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