This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
So below i have an issue that i cant wrap my head around as to why its not working.
The first block of java code works exactly how i wanted it to (e.g. set salary amounts to whatever, and if its not in range give an error and repeat the initial question.)
My problem is this in the second block of code I assumed making a boolean again and emulating the above code to check whether or not my inputs were == "", and if not rinse and repeat like before but it doesnt? i wrote it out exactly the same (of course changing the values) but i simply cant get t to function.
If anyone can help or point me toward the right path id appreciate it :)
//First Block.....
boolean salaryState = false;
while (salaryState == false){
System.out.print("Salary: ");
salary = (input.nextDouble());
if(salary >= 45000 && salary <= 49999) { //if salary amount in this range
this.coachCategory = "Junior"; //then set coaches category to this
salaryState = true;
}
else if(salary >= 50000 && salary <= 59999) { //if salary amount in this range
this.coachCategory = "Youth"; //then set coaches category to this
salaryState = true;
}
else if(salary >= 60000 && salary <= 70000) { //if salary amount in this range
this.coachCategory = "Senior"; //then set coaches category to this
salaryState = true;
}
else { //if invalid salary amount then print error
if (salary <= 45000 && salary >= 70000);
System.out.println("ERROR: Salary range needs to be within 45 000 - 70 000.");
//Second Block...
boolean isName = false;
while (isName == false) {
System.out.print("Name: ");
name = (input.nextLine());
if(name != "") {
this.name = name;
isName = true;
}
else {
if(name == "");
System.out.println("ERROR: Please enter a name.");
}
Replace
name != "" with "name.length()>0"
Your solution will work.
Here is the full solution:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
String heroname;
Scanner input = new Scanner(System.in);
System.out.println("Hello World");
String name;
boolean isName = false;
while(isName==false){
System.out.println("Name: ");
name = (input.nextLine());
if(name.length()>0){
heroname = name;
isName = true;
}else{
System.out.println("Try Again");
}
}
}
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
I've created a program that asks students' names, years, and the courses they have. The idea is if I press y(yes) it should loop back and ask another student, but in my case, if I enter y, it doesn't ask me. Any tips for beginners?
import java.util.Scanner;
public class Practice{
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
String studentName, another;
int year,choice;
do{
System.out.println("Student name: ");
studentName = scan.nextLine();
System.out.println("Year: ");
year = scan.nextInt();
System.out.println("\t1.BSIT \n\t2.BSCS \n\t3.BSCpE \n\t4.BSN");
System.out.print("Choice: ");
choice = scan.nextInt();
scan.nextLine();
if(choice == 1) {
System.out.println("Course is BSIT");
}
else if(choice == 2 ) {
System.out.println("Course is BSCS");
}
else if(choice == 3 ) {
System.out.println("Course is BSCpE");
}
else if(choice == 4) {
System.out.println("Course is BSN");
}
System.out.println("Another Student? type Y if yes, and N if no");
another = scan.nextLine();
}while((another == "Y") || (another == "y"));
if ((another == "N") || (another == "n"))System.out.println("You are the last student.");
}
}
My suggestion would be to set 'another' to be a boolean
boolean anotherStudent = false;
do
{
if((another.equals("Y") || (another.equals("y") ){
anotherStudent = true;
else if((another.equals("N") || (another.equals("n") ){
anotherStudent = false;
}while(!anotherStudent)
I would also do a else if for if they dont enter a Y or an N.
you must change the comparison operator == to string equals ex
another.equals("Y"). or u cant site the same case
I have minor problem with part of the algorithm in this code. Here is a description of the task:
User types in a choice between the numbers 0,1,5 or 2.
0 ends the program,
1 prompts the user to add a name and email to the 2d array,
5 prints out all of the names and email pairs the user typed in. And
2 allows the user to search for an exact match by typing in the name and in return the program prints out the email of the name the user is looking for.
Problem is with the choice == 2 algorithm. It seems that there is a problem and it does not work properly. No matter what the user types it will always print out "Match is found!" and return the wrong email.
Any suggestions?
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[][] rolodex = new String[257][2];
System.out.println("Welcome!");
int choice;
int p = 0;
String matchValue;
boolean isFound = false;
do {
System.out.println("Please select an option: ");
choice = in.nextInt();
in.nextLine();
if (choice == 1 && p < rolodex.length) {
System.out.println("What's the name?");
rolodex[p][0] = in.nextLine();
System.out.println("What's the email?");
rolodex[p][1] = in.nextLine();
p++;
} else if (choice == 5) {
for (int i = 0; i < p; i++) {
System.out.println("email: " + rolodex[i][1]);
System.out.println("name: " + rolodex[i][0]);
System.out.println("--------------------");
}
} else if (choice == 2) {
System.out.println("Type in the name of the email you want: ");
matchValue = in.nextLine();
for (int i = 0; i < p; i++) {
if (matchValue.equals(rolodex[i][0]) && !isFound) {
isFound = true;
}
if (isFound) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
} else {
System.out.println("Match not found!");
}
}
}
} while (choice != 0);
System.out.println("Thank you! Have a nice day!");
}
}
The initializing of the boolean variable and not re-initializing in the following repetitions was causing the problem in your code. Hence, in the block of code I am suggesting below, I have removed the boolean variable altogether. Furthermore, you could try by breaking off from the loop once the correct email match has been identified by the program.
for (int i = 0; i < p; i++) {
if (matchValue.equals(rolodex[i][0])) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
break;
} else if (i == (p - 1)) {
System.out.println("Match not found!");
}
}
You need to reset the value of isFound after it has been set to true. You have not done so, hence the wrong output.
if (isFound) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
//Add this to your code
isFound = false;
}
There is another problem with your search. You have to stop the loop once the match has been found. You have not done so.
I do suggest you try to do it on your own. You should also check #Ayyan Tahzib answer as it contains a hint on correcting this problem of your searching procedure.
If you face any problems, do comment. I will be happy to help you.
Coding a simple HiLo card game where the user is given a card value from a deck of cards and then inputs 'higher', 'lower' or 'equal' trying to guess the balue of the next card.
Just really can't get my head around user input validation with iteration ie. not moving on until a string with the required parameters has been entered.
My code so far:
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
Random randomCard = new Random();
int numberOfSuccesses = 0;
boolean finished = false;
int card = (randomCard.nextInt(13) + 2);
while (finished != true) {
int nextCard = (randomCard.nextInt(13) + 2);
String pictureCard = "";
if (((numberOfSuccesses < 0) ? nextCard : card) == 11) {
pictureCard = "Jack";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 12) {
pictureCard = "Queen";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 13) {
pictureCard = "King";
} else if (((numberOfSuccesses < 0) ? nextCard : card) == 14) {
pictureCard = "Ace";
}
System.out.println("The card is a " + ((card > 10) ? pictureCard : card));
if (numberOfSuccesses == 4) {
System.out.println("Congratulations. You got them all correct");
finished = true;
break;
}
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
String userGuess = reader.nextLine().toLowerCase();
//TODO validate input
if (userGuess.equals("higher")) {
if (nextCard > card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("lower")) {
if (nextCard < card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
} else if (userGuess.equals("equal")) {
if (nextCard == card) {
numberOfSuccesses++;
} else {
finished = true;
break;
}
}
System.out.println(numberOfSuccesses);
card = nextCard;
}
if (numberOfSuccesses < 4) {
System.out.println("Sorry, incorrect!");
}
}
}
and the relevant code extract:
while (!reader.nextLine().toLowerCase().equals("higher")
|| !reader.nextLine().toLowerCase().equals("lower")
|| !reader.nextLine().toLowerCase().equals("equal")) {
System.out.println("Try again!");
reader.next();
}
It kinda just gets stuck at the above part giving "Try again" over and. I've completed programs having to use .hasNextInt() but I'm struggling with this string validation.
Thanks for any and all help/comments!
You are calling reader.nextLine() up to 3 times and so you are comparing 3 different strings.
If I enter "xxx" your code says "xxx != higher so read another line" - it never compares "xxx" to "lower" or "equal".
Also pay attention to && vs ||.
Solution is to read one line into a variable and use that variable for each condition. I'm not going to write it out as this is clearly homework or a self learning exercise, so best for you to do it yourself.
I think your condition logic needs to change. You are checking if input not equal to "higher" or not equal to "lower" or not equal to "equal" so it will always be false overall even if you enter expected value - if you enter "higher" it's not equal to lower. You need to change ors to ands.
I have just recently started coding and am quite the beginner. I'm trying to make a program that simply asks the user to enter a "password", and depending on whether the password is correct; increment a counter. And, once the counter reaches 10, print out a message.
Basically what I'm trying to make is like a "clip-card", like one of those you can get at a coffee shop (you get every 10th coffee free).
So, this is what I have now. I just need to know how to make the program continue after inputting a password, and keep track of the inputs.
Ohhh and... If this is unclear, please say so and I will try to clarify.
This is what I have to far...
import java.util.Scanner;
public class Coffee {
public static void main(String [] args){
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
When would your program end? The way you describe it, it could just go on forever.
If that is the case, you just enclose it in a while loop :
public static void main(String [] args) {
Scanner key;
String moves;
int count = 0;
String pass = "hey";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
}
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
}
if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
But you really should have an breaking condition.
You need loop(while,do-while,or for loop) to do this kind of repeated stuff .
Sample code may help
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
int count = 0;
String pass = "hey";
System.out.println("Enter password: ");
Scanner key = new Scanner(System.in);
String moves = key.nextLine();
boolean flag = true;
while (flag) {
if (moves.compareTo(pass) == 0) {
count++;
System.out
.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if (count == 10 && count != 0) {
System.out.println("You've got a free coffe!");
count=0;
}
if (moves.compareTo(pass) != 0) {
System.out.println("Wrong password! Try again.\n");
}
System.out.println("Do you want to continue ..(y/n)");
String choice = key.nextLine();
if (choice.equals("n")) {
flag = false;
} else {
flag = true;
}
}
}
}
I will give you a while and do-while loop to chose from
While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
while(condition) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
Do-While loop
Scanner key;
String moves;
int count = 0;
String pass = "hey";
boolean condition=true;
do{
System.out.println("Enter password: ");
key = new Scanner(System.in);
moves = key.nextLine();
if(moves.compareTo(pass) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought " + count + " coffe(s)");
if(count % 10 == 0 && count != 0){
System.out.println("You've got a free coffe!");
condition=false;
}
}
else if(moves.compareTo(pass) != 0){
System.out.println("Wrong password! Try again.\n");
}
}while(condition);
I'm trying to have a user enter an input (their name and age, obviously) and if they're younger than 10 or older than 100, I want it to return back to the start and ask them for their age again, until the condition has been met, and then go on to ask the users name. I know how to do that, a boolean. What I don't know how to do is to implement that into my if/else statements. Could anyone help me?
public class Person {
public static void main(final String[] args) {
int age;
String name;
Scanner scan = new Scanner(System.in);
System.out.println("Enter in your age.");
age = scan.nextInt();
if ((age >= 10) && (age < 18)) {
System.out.println("So you're a kid, huh?");
} else if (age < 10) {
System.out.println("How old are you really?");
} else if ((age >= 18) && (age <= 100)) {
System.out.println("So you're an adult, huh?");
} else if (age > 100) {
System.out.println("How old are you really?");
}
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter in your name");
name = in.nextLine();
System.out.println("So you're " + age + " years old and your name is " + name + "?");
}
}
Use a while loop while the condition is not met:
boolean conditionMet = false;
while(!conditionMet) {
// ...
else if (age >= 18 && age <= 100) {
System.out.println("So you're an adult, huh?");
conditionMet = true; // the condition is met => exit the loop
}
// ...
}
Just put a while loop around your first scan and if statements.
boolean validAge = false;
while (!validAge) {
System.out.println("Enter in your age.");
age = scan.nextInt();
if ((age >= 10) && (age < 18)) {
System.out.println("So you're a kid, huh?");
} else if (age < 10) {
System.out.println("How old are you really?");
} else if ((age >= 18) && (age <= 100)) {
System.out.println("So you're an adult, huh?");
validAge = true;
} else if (age > 100) {
System.out.println("How old are you really?");
}
}
You need a loop:
boolean ageIsCorrect = false;
while (!ageIsCorrect) {
// ask age, if the age is correct, set ageIsCorrect to true
}
Put it inside a while loop
while(age is between your specified critiera)
Roughly something like this:
private static int readAndCheck() {
// read age and validate, upon failure return -1
}
public static void main(final String[] args) {
int age = -1;
while (age == -1) {
age = readAndCheck();
}
System.out.println("So you're " + age + " years old and your name is " + name + "?");
}
You should do that in a while loop. I think it's easier and better than other answers:
int age = 0;
while (age<10 || age>100){
age = scan.nextInt();
}
string username = scan.next();
...
Since you are looping, put the prompting code in a loop. Use a boolean to exit the loop
boolean goodAnswer = false;
do
{
System.out.println("Enter in your age.");
...
if ((age >= 10) && (age 100)
{
... // do not set goodAnswer, because the answer was not good
}
} while (!goodAnswer);
Your code actually needs to be better encapsulated to check the age.
Use a method called isValidAge(age) to return a true or false result and then you can write:
int age = 0;
while(!isValidAge(age)){
System.out.println("Please try again! Not a valid age (for an adult)");
... read in the age using scanner...
}
Generally speaking if else () statements are messy and don't extend well - maintenance wise they are not always the best option.