I wrote the following method, which boolean-return type is again assigned to another boolean in another method in which I call this method.
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while(answer != "y" || answer != "n") {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer == "y") {
b = true;
}
return b;
}
But no matter what I type in (y, n, or any other letter), I always end up in the while-loop again.
It's because you have an or rather than and on your test.
As it's currently coded you are saying:
while the answer isn't "y" or it isn't "n", loop.
which will always be the case.
What you want is:
while the answer isn't "y" and it isn't "n", loop.
which is coded as:
while (answer != "y" && answer != "n") (
Change to this: while(answer != "y" && answer != "n") and your code will work as you expect it to.
I suspect your problem lies here:
while(answer != "y" || answer != "n")
When your answer = "y" it isn't = "n" so the loop continues and vice verse.
Probably you want this:
while(answer != "y" && answer != "n")
I changed your code a bit to accept a char instead.
Here is the code:
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
char answer = input.nextLine().toLowerCase().charAt(0);
while(answer != 'y' || answer != 'n' ) {
System.out.println("Answer with y (yes) or n (no)");
//lower case so that it will get y or n, no matter what the casing is
answer = input.nextLine().toLowerCase().charAt(0);
}
if (answer == 'y') {
b = true;
}
return b;
}
or if you really want a string
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while( !(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n")) ) {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer.equalsIgnoreCase("y")) {
b = true;
}
return b;
}
Remember to use .equals() or .equalsIgnoreCase() when comparing two Strings
Related
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
b = scan.next().charAt(0);
if (Character.toString(b).matches("^[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I have this method that checks whether the input is a letter in the alphabet or not, but I want to make sure that the input from the user is not null and that the user only enters one letter. For example "A" or "a" is a correct char, the problem is if I enter "Abcdef" then it is still true as the first letter is still a valid char. I want to make it so that the user can only enter one char, I think I've done that by using the scanner and charAt(0) but is there a more efficient way to do it, and I'm also not sure how to make it so that the input isn't null.
I've revised your code to do what you wanted:
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
EDIT
Without scanner (see comments):
public static boolean correctchar(char b, String input) {
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I made couple of changes :
If invalid input ask user to enter again.
Make sure to close the scanner scan.close()
Scanner scan = new Scanner(System.in);
System.out.println("Please enter only one character : ");
String input = scan.next();
while (null == input || input.isEmpty() || input.length() > 1) {
System.out.println("Invaid Input, Please enter only one character : ");
input = scan.next();
}
scan.close();
if (Character.toString(input.charAt(0)).matches("^[a-zA-Z]")) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
public static boolean correctChar() {
try (Scanner scan = new Scanner(System.in)) {
String input = null;
do {
input = scan.next();
if (input != null && input.length() == 1) {
boolean isCorrect = input.matches("[a-zA-Z]");
System.out.println(isCorrect ? "True" : "False");
return isCorrect;
} else {
System.out.println("Insert only one character");
}
} while (true);
}
}
Looking to do something like in C#:
bool walkable = t.Type == TileType.Green ? true : false;
but in Java
Boolean international_F = (in.next() == 'Y') ? true : false;
The above is what I've tried so far. Wondering if it's even possible.
EDIT: I just noticed .nextChar() doesn't exist. Edited snippet to reflect that.
"nextChar": Assuming in is a Scanner, your issue is that Scanner doesn't have a nextChar() method. You could read a whole word, and then take it's first char:
char theChar = in.next().charAt(0)
boolean vs ternery: If your outputs are true/false, then you don't need an if. You can just write:
bool walkable = t.Type == TileType.Green; // C#
boolean international_F = in.next().charAt(0) == 'Y'` // Java
boolean vs Boolean: Please also note that boolean is the primitive boolean type in Java. Using Boolean will force it to be wrapped as the Boolean class.
case sensitivity: If you want to allow 'y' or 'Y', force the input to a known case first. Since charAt() returns primitive char, you need to use the static Character.toUpperCase().
Solution:
boolean isY = Character.toUpperCase(in.next().charAt(0)) == 'Y'
// - OR -
boolean isY = in.next().startsWith("Y") // not case-insensitive
Boolean international_F = "Y".equals(in.next()); // next returns a string
Boolean international_F =in.next().charAt(0) == 'Y';
You do not need a ternary operator to simply assign the result (true/false) of the evaluation of the condition. You need a ternary operator if you want to do something based on the result of the evaluation of the condition e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Do you want to continue? [Y/N]: ");
boolean yes = in.nextLine().toUpperCase().charAt(0) == 'Y';
if (yes) {
System.out.println("You have chosen to continue");
} else {
System.out.println("You have chosen to stop");
}
// Or simply
System.out.print("Do you want to continue? [Y/N]: ");
if (in.nextLine().toUpperCase().charAt(0) == 'Y') {
System.out.println("You have chosen to continue");
} else {
System.out.println("You have chosen to stop");
}
// You can use ternary operator if you want to do something based on the result
// of evaluation of the condition e.g.
System.out.print("Do you want to continue? [Y/N]: ");
String response = in.nextLine().toUpperCase().charAt(0) == 'Y' ? "Yes" : "No";
System.out.println(response);
// Without a ternary operator, you would write it as:
System.out.print("Do you want to continue? [Y/N]: ");
String res;
char ch = in.nextLine().toUpperCase().charAt(0);
if (ch == 'Y') {
res = "Yes";
} else {
res = "No";
}
System.out.println(res);
}
}
A sample run:
Do you want to continue? [Y/N]: y
You have chosen to continue
Do you want to continue? [Y/N]: n
You have chosen to stop
Do you want to continue? [Y/N]: y
Yes
Do you want to continue? [Y/N]: n
No
This is an example demonstrating what you want to do:
char a = 'a';
char b = 'b';
Boolean b1 = (a == 'a') ? true : false;
Boolean b2 = (a == b) ? true : false;
System.out.println(b1);
System.out.println(b2);
The output will be:
true
false
I created a program that convert text to ASCII value and now when i press Y to try again and input a new string there will be a error that string is out of range etc.
I am new in this field, I will appreciate your help.
And here is the Error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 17,length 17
at java.base/java.lang.String.checkIndex(String.java:3278)
at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:307)
at java.base/java.lang.StringBuffer.charAt(StringBuffer.java:242)
at com.company.Main.main(Main.java:26)
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
boolean Flag; // The Boolean variable for the do while lopp
int n,l,j=0,m,i,ch;
char t;
StringBuffer data = new StringBuffer();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter any string and it will convert into numbers:- ");
data.append(input.nextLine());
l = data.length();
m = l;
System.out.println(l);
for (i = 0; i < m; i++) {
t = data.charAt(j);
n = (int) t;
System.out.print(n);
System.out.print(",");
j++;
}
data.delete(0, m-1);
System.out.println("\nDo you want to try again? Y/N");
ch = input.nextInt();
//Those are the condition for that the program should be run again or not
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
}
while(Flag=true);
System.out.println("Thanks, Come Again");
}
}
while(Flag=true);
this doesn't check whether the value of Flag is true, it sets it to true, and thus automatically returns true.
What you want is:
while(Flag==true);
or,
while(Flag);
for short.
You may also want to read up about naming conventions.
As for your Exception:
Y is not an int, change your
ch = input.nextInt();
to
ch = input.nextLine().charAt(0);
this will solve the initial problem, but still might lead to false results with unexpected input (or lack there of)
int n,l,j=0,m,i,ch;
This declaration is invalid. If all of these values are supposed to be
0, the declaration should look like:
int n, l, j, m, i, ch = 0
Also your logic in the nextInput section is incorrect.
if (ch == 'Y' && ch == 'y')
Flag = true;
else if (ch == 'N' && ch == 'n')
Flag = true;
else
Flag = false;
Instead of the AND ( && ) this should be an OR ( || ). If it's 'Y' OR it's 'y'. It will likely never be both Y and y. This should be fixed as follows:
if (ch == 'Y' || ch == 'y') {
Flag = true;
} else if (ch == 'N' || ch == 'n') {
Flag = false;
}
Also, as mentioned by #Stultuske, you'll want to change your while condition to:
while (Flag == true)
One thing that's niggling at me here is that ch is an integer, but you're asking it if that value is 'Y, y, N, n' those are characters and not integers. I'm guessing that's why you got the 'Input_Mismatch_Exception'. Hope this helps.
Edit: Formatting
I am trying to get my loop to end when the user inputs the character N or n but when I run my program it will not end properly. It seems like the char for answer isn't being read by the loop itself so can someone please help me?
import java.util.Scanner;
public class Project4_Baker
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
char answer;
System.out.println("=============");
System.out.println("Prime or Not?");
System.out.println("=============");
do
{
System.out.print("Enter a whole number ==>");
int n = s.nextInt();
System.out.println();
if(isPrime(n))
{
System.out.println(n + " is a prime number.");
}
else
{
System.out.println(n + " is a composite number.");
}
System.out.println();
System.out.print("Do another (Y/N)==>");
answer = s.next().charAt(0);
}while(answer != 'N'|| answer != 'n');
}
public static boolean isPrime(int n)
{
if(n <= 1)
{
return false;
}
for (int i = 2; i < Math.sqrt(n); i++)
{
if (n%i==0)
{
return false;
}
}
return true;
}
}
my code will not end when it is supposed to
It should be while(answer != 'N' && answer != 'n');. With while(answer != 'N' || answer != 'n');, if somebody inputs N then it will continue because answer is equal to N but it is not equal to n.
try
while(answer != 'N' && answer != 'n');
You want the case where the character is NOT EQUAL to 'N' AND is also NOT EQUAL to 'n'
The problem resides in the loop condition.
while(answer != 'N' || answer != 'n')
The condition above will always be true.
Use this instead:
while(answer == 'Y' || answer == 'y')
You try to compare String with Char in your while lopp statement.
Convert your char to int and use unicode table to look up charcode, ex. n would be 110
Before your loop:
int a = 0;
Whithin your loop:
a = (int)answer;
...(while a != 110 || ...)
This code is a snippet from a Blackjack game I'm making. No matter what I enter, the program never breaks out of a loop.
boolean bool = true;
do{
Scanner kb = new Scanner(System.in);
String choice = kb.next();
if(choice == "Hit" || choice == "hit") {
String action = "hit";
bool = false;
} else if(choice == "Stay" || choice == "stay") {
String action = "stay";
bool = false;
} else {
System.out.println("Do not recognize response. Retry.");
}
} while (bool == true);
What normally happens:
http://puu.sh/87KZk.png
Any help would be appreciated. Thanks!
You are comparing strings with ==. In Java we compare strings with .equals() instead.
You can do something like this:
boolean bool = true;
do {
Scanner kb = new Scanner(System.in);
String choice = kb.next();
if(choice.equals("Hit") || choice.equals("hit")) {
String action = "hit";
bool = false;
} else if(choice.equals("Stay") || choice.equals("stay")) {
String action = "stay";
bool = false;
} else {
System.out.println("Do not recognize response. Retry.");
}
} while (bool == true);
I also formatted some parts of your code for clarity.
As suggested in the comments below, you can also use equalsIgnoreCase to compare string regardless of their capitalization.
Hope this helps!