How do you test the value of charAt(0)? - java

So I am writing a code that ask a user if they would like to be recommended a new pet. I give them a message dialog the ask them to enter Y for Yes and N for No. This is my code do far and there is something I am not getting. The big question is how do I test if the value they entered is Y or N. The answer they give can either be lower case or upper case. How do I code this?
public static void aPet()
{
char answer;
String newPet;
newPet = JOptionPane.showInputDialog(null,"Would you like to recommend another pet?(Y), or Stop (N)","Another Recommendation?", JOptionPane.QUESTION_MESSAGE);
answer = newPet.charAt(0);
if (answer == y || answer == Y)
{
//methods to recommend pet
}
if (answer == n || answer == N)
{
System.exit(-1);
}
}

You need to use actual character literals, not just the letter:
if (answer == 'y' || answer == 'Y')
Characters are denoted in code by surrounding the letter with single quotes (they can also be denoted in other ways, but this is the simplest).
You can read about this on The Java Tutorials > Primitive Data Types which says, among other things:
Always use 'single quotes' for char literals and "double quotes" for String literals.

You are missing single quotes around the values 'y' and 'n':
Try this:
char answer = newPet.charAt(0);
if('y' == answer || 'Y' == answer) {
// recommend pet
} else {
// exit
}
OR
Edited
if(newPet.matches("y|Y")) {
// recommend pet
} else {
// exit
}
OR
if("y".equalsIgnoreCase(newPet)) {
// recommend pet
} else {
// exit
}

You can use Character#toUpperCase() like that:
if (Character.toUpperCase(answer) == 'Y')
{
//methods to recommend pet
}

Related

The operator || is undefined for the argument type

Java is really confusing me with its brackets and variables and I know with just a little help I can understand what the problem is and get on with it.
if(value1=||
Is where the error is.
Apologize in advance that indenting 8 spaces appears to have not had this pull in correctly either. help with that also appreciated...
import java.util.Scanner;
public class WTF {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("Please enter your Character");
String value1 =input.toString();
if (value1 ="a"||"A"||"e"||"E"||"i"||"I"||"o"||"O"||"u"||"U") {
System.out.print("You entered " +value1);
}
else System.out.print("Consonant");
}
}
You will have to check for every string seperately:
if (value1=="a"||value1=="A"||value1=="e"||value1=="E"||value1=="i"||value1=="I"||value1=="o"||value1=="O"||value1=="u"||value1=="U")
but this will most likely not work since == checks for identity on objects and not equality and String is an object. So you would have to write it like this:
if (value1.equals("a") || value1.equals("A") || value1.equals("e") || value1.equals("E") || value1.equals("i") || value1.equals("I") || value1.equals("o") || value1.equals("O") || value1.equals("u") || value1.equals("U")
This is just getting painfull so you could reduce this by setting value1 to upercase and just check for upercase values:
String value1_tmp = value1.toUperCase();
if (value1_tmp.equals("A") || value1_tmp.equals("E") || value1_tmp.equals("I") || value1_tmp.equals("O") || || value1_tmp.equals("U")
This is still kinda ugly so we can improve it by putting it in a method and using a switch statement
private static boolean isVowel(String s) {
switch(s.toUperCase()) {
case "A":
case "E":
case "I":
case "O":
case "U":
return true;
default:
return false;
}
}
and then use this method in your if check:
if (isVowel(value1)) { ...
Or if you are a fan of regular expressions simply do:
if (value1.matches("(?i)[aeiou]")) { ...
So many options, just choose one :)
EDIT: Also fix what Djehenghizz mentioned. Instead of
String value1 = input.toString();
do
String value1 = input.nextLine();
Also, change String value1=input.toString(); into String value1=input.nextLine(); because input is already string, you dont have to transform it.
|| Logical OR Operator only used to combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true.
here what you trying to do is using || between two character types. so It will raise an compile time error actually.
Right Way to check is ==>
Scanner reader = new Scanner(System.in);
char c = reader.nextChar(); //Correct way to Read Char from Console.
private boolean checkVowel(char c) {
switch(c) {
case 'A':
case 'a'
case 'E':
case 'e'
case 'I':
case 'i'
case 'O':
case 'o':
case 'u':
case 'U':
return true;
default:
return false;
}
}
Use below code
public static void main(String[] args) {
List<String> vowelsList = Arrays.asList("a","A","e","E","i","I","o","O","u","U" );
Scanner input =new Scanner(System.in);
System.out.println("Please enter your Character");
String value1 = input.next();
if (vowelsList.contains(value1)) {
System.out.print("You entered " +value1);
}
else System.out.print("Consonant");
}
Try
if (value1=="a"||value1=="A"||value1=="e"||value1=="E"||value1=="i"||value1=="I"||value1=="o"||value1=="O"||value1=="u"||value1=="U") //...
Or
if ("aeiouAEIOU".contains(value1))//...
String value1 =input.toString();
it means use get the info about the input -- a instance of Scanner Class ,the target of it is not what you input.
you may use
String value1 = input.next();
or
String value1 = input.nextLine();
Boolean operator is used to check the value of two boolean variables and returns a boolean value here you are using the operator to compare two strings which is not compatible.
as said earlier you used input.toString method to get the instance of the scanner class but it's not compatilbe instead of that you can use input.Read() or input.ReadLine().
For Strings you should use the .equals("Your Text here") method. should look like this:
if(value1.equals("a")||value1.equals("A")||value1.equals("e"))
and so on.

How to check if one out of four strings have been entered?

I am looking for a statement that checks if the input is either: yes, y, no, n.
It should also ignore whether or not there are big or small letters. I have been searching here for a while but couldn't find an answer I understood. Is there a way to add more then just "yes" to the if statement?
String result;
do {
System.out.print("Bigger the better");
result = scanner.nextLine();
if (!("yes".equals(result))) {
System.out.println("Invalid answer, try again");
}
} while(!result.matches("[A-ZÅÄÖa-zåäö]+"));
You could use
if (result.matches("(?i)Y(es)?|N(o)?")) {
...
You can OR your conditions using double pipes ||, like so:
if (result.equals("yes") || result.equals("no") || result.equals("y") || result.equals("n"))
Make your result a lower case by:
result.toLowerCase()
And then you can compare to any of the strings ("yes","no","y","n") by using equals() as you did, and using 'or' (||).
result.toLowerCase();
if(result.length()>1 && !result.equals("yes") &&!result.equals("no")){
System.out.println("wrong input");
} else if(result.charAt(0)=='y') {
System.out.println("good answer");
}else if(result.charAt(0)=='n') {
System.out.println("Invalid answer, try again");
}
it will check ether the user will type "yes" or plain "y", or "no" or plain "n"

Making a Y/N Condition work

I need help with a SIMPLE Y/N Condition for my program. I don't really get it to work as I want to.
Unfortunately all the other topics I find is very confusing. I'm a very novice student in programming.
I want a Y/N Condition that wont crash and is not CASE SENSITIVE. so if Y or y it goes back to another menu, if n and N is just stop the program and if anything else is typed in it will loop until the Y or N conditions are met.
This is what i wrote:
String input = ScanString.nextLine();
while (!"Y".equals(input) || !"y".equals(input) || !"N".equals(input) || !"n".equals(input)) {
System.out.println("Please enter Y/N (Not case sensitive): ");
input = ScanString.nextLine();
}
if ("Y".equals(input) || "y".equals(input)) {
meny1();
} else if ("N".equals(input) || "n".equals(input)) {
}
When it runs, whatever I put in, it won't break the while loop.
while (!"Y".equals(input) || !"y".equals(input) ||... means "keep looping while the input isn't 'Y' or the input isn't 'y' or...". By definition, one of those conditions will always be true.
The simplest way to do what you're looking for would be a case insensitive comparison, and an and (&&) rather than or operator:
while (!input.equalsIgnoreCase("Y") && !input.equalsIgnoreCase("N")) {
That means "keep looping while the input isn't 'Y' or 'y' and the input isn't 'N' or 'n'.
Or the same in Yoda-speak, since you were using Yoda-speak:
while (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) {
Try this
while (!("Y".equalsIgnoreCase(input)) && !("N".equalsIgnoreCase(input))) {
}
Or
String[] validInputs = { "Y", "N" };
while(!Arrays.asList(validInputs).contains(input.toUpperCase())) {
}

For loop and charAt problems, trying to determine whether a string is numeric [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to write a program is for checking a real number, so i input "99aa", it says it is a right, but in fact, it should be wrong. i have check many time and i still can't fix the problem. can some one give me some hints?
public class jj {
public static void main( String[] args ) {
String num;
// Create a Scanner object for console input
Scanner input = new Scanner(System.in);
System.out.print("Enter the number: ");
num = new String( input.nextLine() );
for ( int i=0; i<=num.length(); i++ ) {
int j = num.charAt(i);
if (j>57 || j<42 || j==44 || j==47 ) {
System.out.print("This is not a real number.");
break;
} else
System.out.print("This is a real number.");
break;
}
}
}
I commented what's wrong with your logic but don't reinvent the wheel.
Use NumberUtils.isNumber from org.apache.commons.lang.math.NumberUtils :
Checks whether the String a valid Java number.
Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).
if(NumberUtils.isNumber(num))
System.out.println("This is a valid number");
else
System.out.println("This is not a valid number");
Alternatively, if you want to check that you have only digits in your String, you can use
NumberUtils.isDigits:
Checks whether the String contains only digit characters.
boolean valid = NumberUtils.isDigits(num);
Your logic is wrong.
try this instead
if ((j >= 48 && j <= 57) || j==44 || j==47 ) {
}
You want to check whether it is between 48 (0) and 57 (9), boundaries included.
See the ascii table.
Sidenotes:
You're allowing j==47. 47 is /, dot is 46. What one do you want?
Your second break; will leave the iteration after the first cycle.
Try,
char ch = num.charAt(i);
if (!Character.isDigit(ch)) {
System.out.print("This is not a real number.");
break;
}
I'd just like to point out some logic trouble that's giving you some fits:
if (j>57 || j<42 || j==44 || j==47 ) {
System.out.print("This is not a real number.");
break;
} else
System.out.print("This is a real number.");
break;
}
First of all, nevermind the problems with the if check. Jeroen Vannevel's answer covers this.
After any number returns true on the if check, you print the error and break; the loop. This is fine (assuming we fix the if check). You don't need to check every digit if you know the first one is wrong, you can quit checking.
But your else prints a message guaranteeing that the whole number is real despite just checking a single letter.
And then the break; isn't contain in the if or the else (not your brackets and my indentation that makes it more clear). No matter what happens, you'll break; after a single iteration.
What you need should look something more like this:
boolean numberFlag = true;
for ( int i=0; i<=num.length(); i++ ) {
int j = num.charAt(i);
if ((j >= 48 && j <= 57) || j==44 || j==47 ) {
numberFlag = false;
break;
}
}
if(numberFlag) {
// logic when a valid number is checked
} else {
// logic when an invalid number is checked
}
We can't say whether num is a valid number of not until we've checked every single character in the string.
And please be sure to check #ZouZou's answer, as this is what you should really be doing.
You could think about this in terms of Characters and implement the following:
if (Character.isDigit(num.charAt(i))) {
//do something
}

check string for integers?

Ok, I posted once earlier but it was locked due to not demonstrating a basic understanding, and the answers I did get before it was locked didn't help me. I'm at a super beginner level of java and this is what I want my program to do (will post code at end). I want the user to input anything they want. Then, if it is not a number, I want it to display that they need to input a number. Then, after they input a number, I want it to display whether or not that number is even or odd. I read about parseInt and parseDouble but i can't figure out how to get it to work how I want. I am not sure any more if parsing is what i want to do. I dont want to instantly convert it to numbers, just to check if it IS a number. then i can proceed to do things after the program has determined if it is a character or number. thanks for any help and let me know if you need more information!
ok i changed some things and used a lot of code from no_answer_not_upvoted. here is what i have now. it runs fine and works with negative and positive whole numbers as specified in the directions. the only thing that bugs me is after all is said and done, i get this error in the compile box at the bottom of eclipse. the program does what is intended and stops appropriately but i dont understand why i am getting this error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at monty.firsttry2.main(firsttry2.java:21)
public static void main(String[] args) {
System.out.print("Enter a character or number. This program will run until you enter a whole number, then it will"
+ "tell you if it was even or odd.");
while (true) {
Scanner in=new Scanner(System.in);
int num;
while(true) {
String input=in.nextLine();
try {
num=Integer.parseInt(input);
break;
}
catch (NumberFormatException e) {System.out.print("That wasn't a whole number. Program continuing.");}
}
if (num==0) {System.out.print("Your number is zero, so not really even or odd?");}
else if (num%2!=0){System.out.print("Your number is odd.");}
else {System.out.print("Your number is even");}
in.close();
}
}
}
Assumption
A String is to be considered a number if it consists of a sequence of digits (0-9), and no other characters, except possibly an initial - sign. Whereas I understand that this allows Strings such as "-0" and "007", which we might not want to consider as numbers, I needed some assumptions to start with. This solution is here to demonstrate a technique.
Solution
import java.util.Scanner;
public class EvensAndOdds {
public static final String NUMBER_REGEXP = "-?\\d+";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(;;) { // Loop forever
System.out.println("Enter a number, some text, or type quit");
String response = input.nextLine();
if (response.equals("quit")) {
input.close();
return;
}
if (response.matches(NUMBER_REGEXP)) { // If response is a number
String lastDigit = response.substring(response.length() - 1);
if ("02468".contains(lastDigit)) {
System.out.println("That is an even number");
} else {
System.out.println("That is an odd number");
}
} else {
System.out.println("That is not a number");
}
}
}
}
Justification
This solution will match a number of ANY length, not just one that will fit into an int or a long; so it is superior to using Integer.parseInt or Long.parseLong, which both fail if the number is too long. This approach can also be adapted to more complicated rules about what constitutes a number; for example, if we decided to allow numbers with comma separators (such as "12,345" which currently will be treated as not a number); or if we decided to disallow numbers with leading zeroes (such as "0123", which currently will be treated as a number). This makes the approach more versatile than using Integer.parseInt or Long.parseLong, which both come with a fixed set of rules.
Regular expression explanation
A regular expression is a pattern that can be used to match part of, or all of a String. The regular expression used here is -?\d+ and this warrants some explanation. The symbol ? means "maybe". So -? means "maybe a hyphen". The symbol \d means "a digit". The symbol + means "any number of these (one or more)". So \d+ means "any number of digits". The expression -?\d+ therefore means "an optional hyphen, and then any number of digits afterwards". When we write it in a Java program, we need to double the \ character, because the Java compiler treats \ as an escape character.
There are lots of different symbols that can be used in a regular expression. Refer to http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html for them all.
this shows you how to do it
import java.util.Scanner;
public class EvenOdd {
public static void main(String[] args) {
System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
try (Scanner in = new Scanner(System.in)) {
int n;
while (true) {
String input=in.nextLine();
try {
n = Integer.parseInt(input);
break;
} catch (NumberFormatException e) {
System.out.println("you did not enter just an integer, please try again");
}
}
if (n % 2 == 0) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
}
}
As is already mentioned in other answers, you will need to call parseDouble statically with
Double theNumber = Double.parseDouble(numberString);
Next you will want to look at wrapping this in a try/catch so that you can do the even/odd check if theNumber is created or set the error message if an exception is caught.
Since you are a beginner, you need to understand the difference between numbers (integers, double, strings, characters), so the following will guide you.
First, read input one line at a time,
Java read line from file)
Then scan line looking for characters that form what you consider to be an integer (allow leading spaces?, then '+' or '-', then digits 0-9, and then trailing spaces.
Here are the rules (for integers)
leading spaces ok (this is up to you) (how: How to check if a char is equal to an empty space?)
optional single '+' or '-'
one or more digits (how: How to check if a character in a string is a digit or letter)
optional trailing space(s) (again, this is up to you)
Anything other than this pattern violates the test for 'is this an integer'. Btw, Double is an extended precision real number.
import java.lang.*;
import java.util.Scanner;
public class read_int
{
public static boolean isa_digit(char ch) {
//left as exercise for OP
if( ch >= '0' && ch <= '9' ) return true;
return false;
}
public static boolean isa_space(char ch) {
//left as exercise for OP
if( ch == ' ' || ch == '\t' || ch == '\n' ) return true;
return false;
}
public static boolean isa_integer(String input) {
//spaces, then +/-, then digits, then spaces, then done
boolean result=false;
int index=0;
while( index<input.length() ) {
if( isa_space(input.charAt(index)) ) { index++; } //skip space
else break;
}
if( index<input.length() ) {
if( input.charAt(index) == '+' ) { index++; }
else if( input.charAt(index) == '-' ) { index++; }
}
if( index<input.length() ) {
if( isa_digit(input.charAt(index)) ) {
result=true;
index++;
while ( isa_digit(input.charAt(index)) ) { index++; }
}
}
//do you want to examine rest?
while( index<input.length() ) {
if( !isa_space(input.charAt(index)) ) { result=false; break; }
index++;
}
return result;
}
public static void main(String[] args) {
System.out.print("Enter a character or number. Seriously, though, it is meant to be a number, but you can put whatever you want here. If it isn't a number however, you will get an error message.");
Scanner in=new Scanner(System.in);
String input=in.nextLine();
if( isa_integer(input) ) {
System.out.print("Isa number.");
}
else {
System.out.print("Not a number.");
}
}
}

Categories