The good usage of Boolean.valuesOf() - java

I have a question about the use of Boolean.valueOf(String). In my code the user will answer a question by entering either true or false. Then the String should be converted to a boolean.
public String setCorrespondingAuthor ()
{
String respons = "true";
do
{
System.out.print("Is s/he the corresponding author? (true/false)");
respons = sc.next();
sc.nextLine();
} while (!respons.equalsIgnoreCase("true")
&& !respons.equalsIgnoreCase("false"));
boolean flag = Boolean.valueOf(respons);
if (!flag)
{
return "not the corresponding author";
}
return "the corresponding author";
}
Right now, it works okay. The problem is that in the output, it prompts the question twice before treat it.

The problem is that you're reading twice from user input: sc.next() and sc.nextLine(). You should only read once and store that value in your respons variable.
You should also consider calling equalsIgnoreCase on String literals( such as "true" , "false") and not on variables, because variables might be null, resulting into a NullPointerException.
String respons = "true";
do
{
System.out.print("Is s/he the corresponding author? (true/false)");
respons = sc.nextLine();
} while (!"true".equalsIgnoreCase(respons)
&& !"false".equalsIgnoreCase(response));
return Boolean.valueOf(respons) ? "the corresponding author" : "not the corresponding author";

Related

How can I create an interactive program that ask for user's full name and display it everytime he wants to try again?

My code looks like this; it get's an error on line 18
error: bad operand types for binary operator '==' if(answer=='y'||answer=='Y') {
import java.util.Scanner;
public class FullName {
public static void main(String[]args) {
String firstName = " ", middleName = " ", lastName = " ";
String in; // checks for input
String answer; // checks for condition, YES OR NO
boolean ask; // use as a loop switch
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please indicate your full name: ");
in = scan.nextLine();
ask = scan.hasNext(in);
String str = String.format("My name is %s %s %s ", firstName, middleName, lastName);
System.out.println("Do you want to try again? (Y/N )");
answer = scan.Next();
if(answer=='y' || answer=='Y') {
ask = true;
} else {
ask = false;
}
} while(ask == true);
}
}
Let's just focus on these lines:
String answer;
...
answer = scan.next();
if (answer == 'y' || answer == 'Y') {
You will notice that I have tweaked the the style to make it more readable and consist with common Java style rules.
You will notice that I have fixed a compilation error by changing Next() to next().
But now for the interesting part:
answer == 'y' || answer == 'Y'
What you are trying to do here is test if the user is trying to reply in the affirmative or the negative; i.e. a response to your `"(Y/N)" question.
There are both technical and logical problems in the way you are doing it. The technical problem is that answer == 'y' tries to compare a String and a char using ==. Java doesn't allow that.
This is what the compilation error about "bad operand types for ==" is saying.
String and char are different types.
'Y' and "Y" are not the same value.
Expressions of the form "string == char" or "char == string" are not allowed.
You shouldn't compare strings using == anyway; see How do I compare strings in Java?.
So if you were just going to compare (one character) String with a char, there are a few ways to do it; e.g.
answer.charAt(0) == 'y'
or
Character.toString('y').equals(answer)
(In this context charAt(0) is safe. You are using the default Scanner delimiter, so next() is going to return a String with length of at least 1.)
But it would be simpler to do a String to String comparison:
answer.equals("y")
or
"y".equals(answer)
The latter has the advantage in some contexts that "y" can never be null so you will avoid possible NPEs.
Now for the logical problem. You have asked the user to respond to a (Y/N) question. But you are actually using Scanner to read a word (loosely speaking) so you may get one character, or more than one. Also, you are assuming that if the answer is not y or Y, then that means "no". But what if the user enters "yes" ... or "fish"? There are more possible answers to consider than the ones that you are expecting.
If I was marking this exercise, I would deduct a mark or two (out of ten) for not properly validating the user's input.
Since the answer variable is not stored as a string, change its variable type to char.
Also, use the following code to get the letter entered by the user.
answer = scan.next().charAt(0);
Use the following
import java.util.Scanner;
public class FullName {
public static void main(String[]args) {
String firstName = " ", middleName = " ", lastName = " ";
String in; // checks for input
char answer; // checks for condition, YES OR NO
boolean ask; // use as a loop switch
Scanner scan = new Scanner(System.in);
do {
System.out.print("Please indicate your full name: ");
in = scan.nextLine();
//ask = scan.hasNext(in);
String str = String.format("My name is %s %s %s ", firstName, middleName, lastName);
System.out.println("Do you want to try again? (Y/N )");
answer = scan.next().charAt(0);
if(answer=='y' || answer=='Y') {
ask = true;
} else {
ask = false;
}
scan.nextLine();
} while(ask == true);
}
}

How to compare a returned string from a method with another string in the main method?

The idea is that the while loop should loop through the code if the result is "wrong password",
until the correct password is entered and breaks the loop when it matches the login method return value.
while (true){
System.out.println("\nLogin: ");
System.out.println("\nEnter a username: ");
String loginUsername = sc.nextLine();
System.out.println("Enter a password: ");
String loginPassword = sc.nextLine();
System.out.println(login(loginUsername,loginPassword));
if (login(loginUsername,loginPassword).equalsIgnoreCase("Successfully logged in!")) {
break;
}
}
this code is the return statements from the login method
if (check == true){
return ("\nSuccessfully logged in!");
} else {
return ("\nWrong username/password");
}
But "Successfully logged in!" is not the same string as "\nSuccessfully logged in!".
More importantly... Why use strings for this at all? If you want to know whether something is true or false, there's a perfectly good data type to convey that information. Return that type instead:
return check;
Rename the method to something more meaningful than login, and use its result in a semantically clear condition:
if (isLoginSuccessful(loginUsername,loginPassword)) {
break;
}
This puts the semantics of what you're doing in the code itself, rather than in magic strings that you need to copy/paste everywhere and manually keep track of. Which, already in this one tiny example, you've lost track of by making the strings different. (With the added benefit that using booleans for conditional logic probably performs a little better than string comparison.)

Not sure how to use the .equals() method to compare a string in an if statement

System.out.println("\n");
System.out.println("What is the upgrade of your Hammer? You must choose a number.");
System.out.println("1. No Upgrade");
System.out.println("2. Sapphire.");
System.out.println("3. Emerald.");
System.out.println("4. Ruby.");
System.out.println("5. Diamond.");
String var1 = Scanner.nextLine();
//char hammerlevel = (char) System.in.read();
System.out.println();
System.out.println("\n");
double noviceStardustPotion = 6023.33333333; //amount of experience per potion average
if (var1.equals('No Upgrade')
{
}
It was working originally when I used the numbers, but I don't want my users typing a number, I want them to type the actual word.
if (hammerlevel == '1')
{
}
I've researched on the .equals method and I cannot find any examples like mine that use the method with a string in the parentheses
Any ideas or even blatant answers that could help?
First, you're if statement is a bit wonky. It's missing a closing a parenthesis and it should be using " " instead of ' ' to denote a string literal.
if (var1.equals("No Upgrade"))
{
}
And a bit about how equals() works.
String input = "No Upgrade";
String input2 = "no upgrade";
String input3 = "no upgrade";
//this returns false because the strings are not the same value
if (input.equals(input2) {
//do action
}
//this returns true because the string values are the same
if (input.equals("No Upgrade") {
//do action
}
//this returns true because the string values are the same
if (input2.equals(input3) {
//do action
}
The equals method from string is comparing the values of the string. If it has an extra whitespace, an extra capital letter, anything, it won't be true. You can avoid this by using toUpperCase() or toLowerCase() on both strings and then checking their value, or by just using equalsIgnoreCase().
if (input1.equalsIgnoreCase("No Upgrade")) {
}
Cutting down your code to just the relevant bits:
String var1 = Scanner.nextLine();
if (var1.equals('No Upgrade')
{
}
(Everything else is a System.out.println call, or an unused variable)
The only problem with this code is that 'No Upgrade' is not valid Java, and so does not compile: you use single quotes to denote a char literal, and thus you can only have a single character between the quotes, e.g. 'a'.
You use double quotes to specify a String literal:
String var1 = Scanner.nextLine();
if (var1.equals("No Upgrade")
{
}
First, check the input of the user, so the input shouldn´t be something like "you s*ck"
int var1 = Scanner.nextLine().parseInt();
if(var1 == 1){}
if(var1 == 2) //You can also use int, but you don´t want, ok
if (var1.equals("1")) //Because var1 should be a number{}

Java Login Error, can not be resolved to variable

I'm building a log in system for a java program which will be working out employees wages for certain stores.
Before I go any further I am fully aware this isn't the safest way to make a log in so please don't try explaining because I'm aware.
My code so far is below
public class project15
{
public static void main(String[] args);
{
String store = store501;
String stroePin = 1468dty;
String personalPin = abc123;
String inputStore;
String inputPin;
String inputPersonal
inputStore = JOptionPane.showInputDialog("please enter the store number");
inputPin = JOptionPane.showInputDialog("please enter the stores unique ID");
inputPersonal = JOptionPane.showInputDialog("please enter your persoanl ID");
if (inputStore==store && inputPin==stroePin && inputPersonal==personalPin){
System.out.println("correct information");
}
else
{
System.out.println("incorrect information");
}
}
}
I get an error on the first three String values saying, for example, "store501 can not be resolved to a variable. " Everything else seems to be working okay. Can anyone spot where I've gone wrong and please explain as I am eager to learn from any mistakes I may have made. Thanks in advance and I appreciate any feedback.
It seems like store501, 1468dty and abc123 are variables that are not defined.
You must define them before using. Something like:
String store501 = "some string";
Or maybe you want them to be Strings. In that case:
String store = "store501"; // Strings are between ""
Read more about Strings in Java docs, or Java tutorials.
Remember:
To compare String use:
str1.equals(str2)
not
str1 == str2
Read this "How to compare Strings in Java"
There's more than one mistake in your program. First, there's what everybody else said about declaring your String constants. But then there's another mistake too.
You are using == to compare Strings. The Java expression a == b compares two variables and it returns true if both variables reference the same Object. It does not compare the objects to see whether or not they have the same value.
Your program could set personalPin="abc123"; and the user could type in abc123 when prompted for inputPersonal, and yet personalPin and inputPersonal are likely to refer to two different String objects that both happen to have the same value. That is to say, personalPin==inputPersonal could be false even though both strings are "abc123".
The way to fix it is to use the String.equals() function to compare the contents of the Strings:
personalPin.equals(inputPersonal)
Change your code to :
String store = "store501";
String stroePin = "1468dty";
String personalPin = "abc123";
If they are string variables then you should place them within "".You can either do it this way:
String store = "store501";
String stroePin = "1468dty";
String personalPin = "abc123";
OR:
String store;
String stroePin;
String personalPin;
store="store501";
stroePin="1468dty";
personalPin="abc123";
When you create a String you need to surround it with ""
String store = "store501";
String stroePin = "1468dty";
String personalPin = "abc123";
String inputStore;
String inputPin;
String inputPersonal
inputStore = JOptionPane.showInputDialog("please enter the store number");
inputPin = JOptionPane.showInputDialog("please enter the stores unique ID");
inputPersonal = JOptionPane.showInputDialog("please enter your persoanl ID");
if (store.equals(inputStore) && stroePin.equals(inputPin) && personalPin.equals(inputPersonal)){
System.out.println("correct information");
} else {
System.out.println("incorrect information");
}

TextInputFile, TextOutputFile (with username, pass in a login system)

int menuoptions;
String userinput;
String usercheck="";
String username="user";
String password;
int intCounter=0;
con.println("TYPING GAME\n");
con.println("1. Sign in");
con.println("2. Create a new account");
menuoptions = con.readInt();
con.clear();
if(menuoptions==1){
while(!username.equals(usercheck) && intCounter==0){
con.println("Please type in your username.");
userinput = con.readLine();
con.clear();
TextInputFile infile = new TextInputFile("logins.txt");
while(infile.eof() == false && intCounter==0){
usercheck=infile.readLine();
infile.readLine();
if(username.equals(usercheck)){
intCounter=intCounter+1;
}
}
if(!userinput.equals(usercheck) && intCounter==0){
con.println("No such username.");
pause(2000);
con.clear();
}
else if(userinput.equals(usercheck)){
intCounter = intCounter+1;
}
}
con.println("What is your password?");
}
if(menuoptions==2){
con.println("What will be your username?");
username = con.readLine();
con.clear();
con.println("What will be your password?");
password = con.readLine();
con.clear();
TextOutputFile outfile = new TextOutputFile("logins.txt", true);
outfile.println(username);
outfile.println(password);
}
}
public static void pause (int intMS){
try{Thread.sleep(intMS);
}catch(InterruptedException y){}}
In logins.txt, i have 'voidturbulence' in one line, and in the next line, i have '80'.
when i type in 'voidturbulence', it jumps to 'no username found', when it should be asking for the password.
However, if userinput (voidturbulence) is equal to usercheck (the first line [voidturbulence]), then shouldn't it break out of the loop and ask me for the password?
A. The code
usercheck=infile.readLine();
infile.readLine();
looks suspicious to me. You probably have a blank line, a line with the user name, and some other text in the file read by infile. Thus, usercheck probably never receives the user name you target. (You skip every second line from infile.)
B. instead of
infile.eof() == false
use
!infile.eof ()
for better readability.
Otherwise,
(((infile.eof() == false) == true) == true)
would be considered more readable, right?
C. instead of
if (menuoptions == 1)
{
}
if (menuoptions == 2)
{
}
use
if (menuoptions == 1)
{
}
else if (menuoptions == 2)
{
}
since menuoptions cannot equal 2 when you just found it was equal to one (and did not change it in the first then-block).
D. What is intCounter good for?
You initialize it to 0.
You increment it if the username equals
usercheck.
The while loop loops as long as username is not equal to
usercheck and intCounter equals 0.
Thus, both condition will be fullfilled if username equals usercheck.
You could eliminate intCounter.
This is a good example for a bad variable name. "intCounter" neither guarantees that it is an int, nor that it contains a count of anything. You will find that if you try to create useful names, you'll tend to create useful code. In your example, you created a useless name, and useless code that manipulates the value behind the name, but really don't accomplish anything.
E. What are you trying to accomplish?
Except for the headline of the question, there is no specification of the requirements your code tries to cover. Better specify what you want to do, then present the code, and specify your problem. Don´t just throw some general keywords at us, followed by code. Please ;)

Categories

Resources