I'm trying to make my program validate between the use of two single characters that are input by the user, which must be A or M.
Here's my code I have thus far:
static char getCustomerType() {
System.out.println("Please enter the term for the Policy the client would like");
System.out.println("A for Annual or M for Monthly. Annual provides the user with a 10% discount");
String s = inputs.next();
while (s != 'A' && s != 'M') {
System.out.println("Incorrect, please try again");
s = inputs.next();
}
}
Netbeans however, does not like this stating the inputs.next is never used when I have set it to be used before the while statement?
It also doesn't like the while statement producing incompatible string type referencing boolean to string.
I assume this is because I have declared s as a String?
You can have single characeter input from user using below code assuming inputs is your scanner object:
char c = inputs.next(".").charAt(0);
and then you can compare it using != or .equals() or .equalsIgnoreCase()
why not write
while ( ("A".equalsIgnoreCase(s) || "M".equalsIgnoreCase(s)) == false)
Related
I have a method that is supposed to get the input of a String from a user and validate 4 things:
that its only 1 word, doesn't contain spaces, doesn't contain numbers, and isn't blank/had the enter key pressed.
If any of these issues occur then an error msg is printed and the method is called again to re-prompt the user for input. If the string meets the requirements than the method returns the String.
In most cases the method works as intended, however, if I enter an incorrect repsonse the first time around then even after it prompts me with the error and I enter the correct response it returns the incorrect response I entered the first time. Can someone please explain why this is happening?
public static String getName() {
//Prompt User for Name and Store it as the tmp String
System.out.print("Please enter the target string here: ");
String tmp = in.nextLine();
//Check to see if the string is blank, contains more than one word, or contains numbers. If so, give error and re-prompt
if(tmp.equals("") || tmp.contains(" ") || tmp.contains("1") || tmp.contains("2") || tmp.contains("3") || tmp.contains("4")
|| tmp.contains("5") || tmp.contains("6") || tmp.contains("7") || tmp.contains("8") || tmp.contains("9") || tmp.contains("0")) {
System.out.println("\nYou entered an invalid response, please try again\n");
getName();
}
//Return the String
return tmp;
}
You must assign the string:
tmp = getName();
Here is the problem I was given:
Write a program that takes website names as keyboard input until the user types the word 'stop'. The program m just also count how many of the website names are commercial website names (i.e., end with .com), and output that count.
The problem that keeps occurring is even if I type the word stop as input, it is still saying to "enter the next site." I'm not sure where I went wrong.
Can anyone help? Here is my code.
import java.util.Scanner;
public class NewClass
{
public static void main( String [] args)
{
int numberOfComSites = 0;
String commercialNames = "com";
final String SENTINEL = "stop";
String website;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a website, or 'stop' to stop > ");
website = scan.next();
String substring = website.substring(website.length()-3);
while (website != SENTINEL)
{
if(substring == commercialNames)
{ numberOfComSites++;
}
System.out.print( "Enter the next site > ");
website = scan.next();
}
System.out.println( "You entered" + numberOfComSites + "commercial websites.");
}
}
Thanks!
You are using reference equality == to compare strings. You strings are from different sources. SENTINEL comes from constant pool, while website comes from user input. They are always different as references.
To compare strings by value, the equals method should be used. In your case you, should replace
while (website != SENTINEL)
by
while (!SENTINEL.equals(website))
Notice that we compares constant with user input. This address a problem when website is null. This is not the case in your code, but it is a sign of good style.
See What is the difference between == vs equals() in Java? for more information.
replace
while (website != SENTINEL)
with
while(!website.equals(SENTINEL))
website is of String type and is not a primitive type. So you need to use equals method to compare String. == is used for reference comparison.
Refer this for more details What is the difference between == vs equals() in Java?
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed last year.
It executes correctly the first time, but:
It keeps printing "Please try again (Y/N)?" no matter what the
input is after asking to continue.
I am unsure if != is appropriate to use for String comparison. I want to say while
loopChoice "is not" Y or N, keep asking.
while(isLoop) {
// Ask for user input
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextInt();
System.out.print("Enter rate per hour: ");
payRate = scn.nextInt();
scn.nextLine();
// Call functions to compute stuff
...
// Print results
...
System.out.print("\nDo you want to continue (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
while(loopChoice != "Y" || loopChoice != "N") {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
switch(loopChoice) {
case "Y":
isLoop = true;
System.out.print("\n");
break;
case "N":
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
default:
System.out.println("Your input is invalid!");
isLoop = false;
System.out.println("Terminating program...");
scn.close();
System.exit(0);
break;
}
}
You should compare with String equals
while (!loopChoice.equals("Y") && !loopChoice.equals("N"))
Also, replace the or operator with and operator
That's not how you compare strings in Java.
There is also a logical error in your code, as the string can't be both Y and N at the same time, you have to use && instead of ||. As long as the choice is neither Y or N, you want to continue the loop. If it is any of them, you want to stop. So && is the correct choice here.
To check if two strings are equal, you have to use .equals(obj)
while (!loopChoice.equals("Y") && !loopChoice.equals("N")) {
The reason for this is that == compares object references, and two Strings are most often not the same object reference. (Technically, they can be the same object reference, but that's not something you need to worry about now) To be safe, use .equals to compare Strings.
To avoid a possible NullPointerException in other situations, you can also use:
while (!"Y".equals(loopChoice) && !"N".equals(loopChoice)) {
You cannot use loopChoice != "Y", since "Y" is a String. Either use:
loopChoice != 'Y', or
"Y".equals(loopChoice)
Alternatively, use "Y".equalsIgnoreCase(loopChoice).
Case switching is also not possible for Strings if you use Java 1.6 or earlier. Be careful.
You need to know that OR Operation will return true if one of the two condition is true , so logically if you Enter Y , so you ask if the input is not equal Y so the answer is false then you will go to the next part in your condition if the input not equal N so the answer is True , so your finally result will be (True || False = True ) and then you will entered to while loop again
so the true condition is (the input not equal Y && not equal N)
You have fallen into the common early gap between checking equality of objects versus the values of objects. (You can see a quick list of string comparison information [here]
(http://docs.oracle.com/javase/tutorial/java/data/comparestrings.html)
What you wrote asks whether the object loopChoice is the same object as the string constant "Y" or the string constant "N" which will always return false. You want to ask whether the value of object loopChoice is the same as the value of string constant "Y".
You could rewrite your code as follows:
System.out.print("\nDo you want to continue (Y/N)? ");
// get value of next line, and trim whitespace in case use hit the spacebar
loopChoice = scn.nextLine().trim();
while (!("Y".equalsIgnoreCase(loopChoice) || "N".equalsIgnoreCase(loopChoice)) {
System.out.print("\nPlease try again (Y/N)? ");
loopChoice = scn.nextLine().toUpperCase();
}
Note, I like to put the constant value first for clarity. The general form for determining whether the value of two strings is the same is String1.equalsIgnoreCase(String2).
i'm trying to read a line and then go into a if-statement. But after it have red the first input it just terminates.
I have no idea what's wrong, and I can't figure it out
import java.util.Scanner;
public class mainen {
public static void main(String[] args) {
Formler form = new Formler();
Scanner Sscan = new Scanner(System.in);
Scanner Dscan = new Scanner(System.in);
String input;
System.out.println("Formler: Molmassa");
input = Sscan.nextLine();
if(input == "molmassa" || input == "Molmassa"){
double m;
double M;
System.out.println("Massa: "); m = Dscan.nextDouble();
System.out.println("Molmassa: "); M = Dscan.nextDouble();
System.out.println(form.getMolmassa(m, M));
}
}
}
Change your if statement to:
if(input.equalsIgnoreCase("molmassa") ) { }
Then it should work as you expect. Remember always compare strings using equals() or equalsIgnoreCase() method. == compares object references not the actual values.
You need to replace the equals checks:
if(input == "molmassa" || input == "Molmassa"){
with the following;
if(input.equals("molmassa") || input.equals("Molmassa")){
The first checks if the Strings are the same object, whereas the second checks that they're the same value, which is what you need here.
The problem is in you if condition change it to
if(input.equalsIgnoreCase("molmassa) )
and every thing should work fine.
One more thing you don't need to have separate Scanner to take String and double input you can use one Scanner object for both the inputs.
if(input == "molmassa" || input == "Molmassa"){}
You should equal String object with equals method or equalsIgnoreCase method.
if(input.equalsIgnoreCase("Molmassa")){}
== is used for primitive equaling check.
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i; //The important part
System.out.println(integerChar);
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
//Handle yes
} else if (i == 'N') {
//Handle no
} else {
System.out.println("You've mistyped the answer.");
}
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
Use if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) { instead.
Or (as Mark pointed) if (addNewUser.toLowerCase().startsWith("y")) {.
BTW maybe look at Apache Commons CLI?
You cannot convert String to int, unless you know the String contains a valid integer.
Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how Scanner will be used to take input:
import java.util.Scanner; // this is where the Scanner class resides
...
Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y')
{ } // do something
else if(choice == 'N')
{ } // do something
else
System.err.println("Wrong choice!");
This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):
if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
{ } // do something
else // for 'N'
{ } // do something
Secondly, char to int conversion just requires an explicit type
cast:
char ch = 'A';
int i = (int)ch; // explicit type casting, 'i' is now 65 (ascii code of 'A')
Thirdly, even if you take input from a buffered input stream, you
will take input in a String. So extracting the first character from
the string and checking it, simply requires a call to the charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
String s = in.readLine();
if(s.charAt(0) == 'Y') { } // do something
Fourthly, its a very bad idea to put the whole program in a try
block and catch Exception at the end. An IOException can be
thrown by the readline() function, and parseInt() could throw a
NumberFormatException, so you won't be able to handle the 2
exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.