This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm learning the basics of Java, and wanted to practice something. So found a page of some programing problems and I get stuck at this problem:
2) Write a program that asks the user for her name and greets her with her name.
3) Modify the previous program such that only the users Alice and Bob are greeted with their names.
I've made well the 2nd but I have trouble with 3rd one.
System.out.pritnln("Please enter your name ");
Scanner input = user new Scanner(System.in);
String user_name;
user _name = input.next();
if(user_name == "Alice"){
System.out.println("Hello " + user_name + ", sweet name.");
if(user_name=="Bob"){
System.out.println("Hello " + user_name + ", sweet name.");
}
}
Don't use == for string comparison in Java unless you're really sure that is what you are doing. Use:
user_name.equals("Bob")
I actually use equalsIgnoreCase() as my standard approach unless I'm sure it should be case-sensitive.
Related
This question already has answers here:
Local variables of same name in same scope, IDE display error but when I run the program, no run time error results
(3 answers)
Closed 4 years ago.
I just wanted to say that I am new at java and I have been practicing and getting a LITTLE better. I'm trying to make a very simple banking system where you have the options to create an account, deposit and withdraw money. I'm a bit stuck at this current time though and hoping someone could help me out.
I'm trying to take input from the user and then create a new object instance with the user input in the parameters and it's giving me and error. Here is the code line it's giving me the error on, thank you!
It's prompting me with the error on the: bankAccount object creation line for the userName String variable.
case 1:
System.out.println("Please Enter Your Name: ");
String userName = input.nextLine();
System.out.println("Please Enter a 4 digit pin number: ");
int pinNumber = input.nextInt();
int accountNumber = rand.nextInt(5100 - 1100) + 1000;
System.out.println("Account Created with the following credentials:\n " +
"Name: " + userName + "\n" +
"Account Number: " + accountNumber + "\n" +
"Pin Number: " + pinNumber);
bankAccount userName = new bankAccount(userName, accountNumber);
break;
With java, you cannot make a local variable with the same name, even though the data types are different.
userName is already used as a String variable so you cannot make a new bankAccount named userName. You could name it userAccount though.
Example:
bankAccount userAccount = new bankAccount(userName, accountNumber);
You could then add this to an array or Map to reference that particular userAccount later.
bankAccount[] accounts = new bankAccount[];
//several lines of code
bankAccount[0] = userAccount;
or
Map<String, bankAccount> bankAccount accounts = new HashMap<String, bankAcount>();
//several lines of code
bankAccount.put(userAccount.userName, userAccount);
To retrieve the userAccount of a certain user, you can do this later in the program.
bankAccount userAccount = bankAccount.get("bob");
This is get the bankAccount that has "bob" as the userName.
I imagine you're doing this as an independent project. If you have the time, it could be a good idea to learn some java from codecademy to get a better understanding of the basics.
You have created the variable userName twice in line number 2 and 10. in java you cannot create the same variable name even though they have two types.
This question already has answers here:
Output in a table format in Java's System.out
(8 answers)
Closed 5 years ago.
for (int k = 0; k < 7; k++){
System.out.println("Vak/project:\t" + vakNamen[x] + "\t\t"
+ "Cijfer: " + vakCijfers[x] + "\t" + "Behaalde punten: "
+ vakPunten[x]);
x++;
}
EDIT: the assignment wants to use system.out.printf so I will have a look at that, ty for the hint
and the system.out.format seems interesting I never heard of that, will look into it
Ok so my question is in this for loop I print 3 different arrays and I want them to be in a table so I used \t, but the problem u get with this is that if the "vakNamen" which is the name of the subject is LONGER than another then the tabs will go further and create this ugly table:
https://gyazo.com/398953f233f3562eecfa6c483ec73e62
I dont really know how to ask this question but I think I should ask how to make sure \t is independant from the previous lines?
You can use System.out.format()
Example:
String project = "myProjectName";
String firstName = "firstName";
String lastName = "lastName";
System.out.format("%-20s%-15s%-15s", project, firstName, lastName);
Above code snippet should print the following formatted output:
myProjectName firstName lastName
Edit:
I found this library which simplifies such kind of formatting. It is also available on Maven.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
If someone can help me with this. I'm complete -n o o b, only started to learn and got stuck.
If I'm asking this -
Scanner buck = new Scanner(System.in);
String fname;
System.out.println("Please Enter your Name ");
fname = buck.next();
which command do I use to make specific name only to be entered as an answer.
For example name would be Vani.
If name is "Vani" than "you are in".
If any else name "than you go out".
I understand this with numbers but not with letters.
Any help would be appreciated.
To "kick out" if the name is not "Vani":
if("Vani".equals(fname)) { //You can use equalsIgnoreCase instead if you like
System.out.println("You are in.");
} else {
System.out.println("You are out.");
}
To accept input until "Vani" is given:
do {
System.out.println("Please Enter your Name ");
fname = buck.next();
if(!"Vani".equals(fname)) {
System.out.println("You're not Vani!");
}
} while(!"Vani".equals(fname));
if ("Vani".equals(fName)) {
// you go in
} else {
// cannot go in
}
And if you want case insensitive check, do "Vani".equalsIgnoreCase(fName).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
i want to ask a question for a bedsize and while the answer is not what i choose it will be i want that it will ask the user to answer again
import java.util.Scanner;
public static void main(String[] args) {
String newBedType ;
Scanner sc1 = new Scanner(System.in) ;
System.out.println("you want a single bed or doublebed? ") ;
newBedType = sc1.next() ;
while (newBedType != "single" + "doublebed") {
System.out.println("please choose againe the bed size: ");
newBedType = sc1.next() ;
switch (newBedType) {
case "single" : System.out.println("i see you like sleeping alone");
break ;
case "doublebed" : System.out.println("got company ;) ");
break ;
}
}
}
}
the code kinda works it shows the cases if i write the correct string but it will continue to ask me forever.....
i just stared learning java so be easy on me i know its a stupid question but after hours of trying and searching here(though i did found in python but dont know how to "translate" it to java)
i cant figure it out... thanks to anyone willing to help :)
Your issue is with the line:
while (newBedType != "single" + "doublebed")
This doesn't do what you think it does. You are comparing the variable newBedType with the string "singledoublebed", the addition operator is concatenating those two strings. You want the line:
while (!newBedType.equals("single") && !newBedType.equals("doublebed"))
Note the use of the .equals() method, as string comparisons in Java do not act as expected with the == or != operators.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 9 years ago.
So I'm fairly new to Java and I am trying to run a program that will display a certain number of letters from a name and ask the user for a response. The user's response should determine one of two answers ("Correct" or "I'm sorry, that's incorrect").
The problem I'm encountering is that when I run the program and put in the answer that should lead to "Correct," which is 'Billy Joel,' I get the response of "I'm sorry, that's incorrect."
I'm not actually sure what's going on, but here's a link to a picture of the CMD when I input what should lead the system to say "Correct" and instead it says "I'm sorry, that's incorrect":
And here is a copy of the relevant code:
System.out.println("\nLet's play Guess the Celebrity Name.");
String s6 = "Billy Joel";
System.out.println("\n" + s6.substring(2, 7));
Scanner kbReader3 = new Scanner(System.in);
System.out
.print("\nPlease enter a guess for the name of the above celebrity: ");
String response = kbReader3.nextLine();
System.out.println("\nYou entered: \n" + response + "\n");
if ((response == "Billy Joel")) {
// Execute the code here if Billy Joel is entered
System.out.println("\nCorrect!");
} else {
// Execute the code here if Billy Joel is not entered
System.out.println("\nI'm sorry, that's incorrect. The right answer was Billy Joel.");
}
System.out.println("\nThank you for playing!");
There's more before this that the program also does, but I'm not having a problem with any of that and it's all correct. I took out the Billy Joel part and everything else ran exactly as it was supposed to. It's just the above code in relation to what it should put out and what it is putting out that's the problem. I'm wondering if maybe I'm missing something in my code or I put something in wrong, but whatever I did, help would be much appreciated.
Your problem lies here. You are using wrong operator to compare strings
if ((response **==** "Billy Joel")) {
System.out.println("\nCorrect!");
} else { ... }
the correct should be
if ((response.equals("Billy Joel")) {
System.out.println("\nCorrect!");
} else { ... }
To compare strings in java you have to use .equals() operator. And to use '==' operator you need to have int, bool etc.
if (response!=null && response.length>0){
//trim the input to make sure there are any spaces
String trimmed=response.trim();
if (response.equals(s6))
System.out.println("\nCorrect!");
} else { ... }