While loop JOptionPane issues - java

Ok - I know that I am fairly close to the solution but need a nudge in the right direction. I need the user to hit YES and the program to begin asking the question again.
After execution, I get the following errors
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 1 at java.lang.String.charAt(Unknown
Source) at Vowel3.main(Vowel3.java:49)
// java class for Panel I/O
import javax.swing.JOptionPane;
// declaration of the class
public class Vowel33
{
// declaration of main program
public static void main(String[] args)
{
// objects used to store data
String input_string = null;
int a_count = 0;
int e_count = 0;
int i_count = 0;
int o_count = 0;
int u_count = 0;
int i = 0;
int yes = 0;
// 1. display a descriptive message
String display_message = "This program asks the user for a sentence,\n"
+ "searches the sentence for all vowels,\n"
+ "and displays the number of times each"
+ "vowel appears in the sentence";
JOptionPane.showMessageDialog(null, display_message, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);
// 4. visit each String posotion
do{
// 3. input the character string
input_string = JOptionPane.showInputDialog("Enter the sentence to search");
// 5. if position i of String is a vowel
// 6. increase the appropriate vowel counter
if (input_string.charAt(i) == 'a' || input_string.charAt(i) == 'A')
a_count++;
else if (input_string.charAt(i) == 'e' || input_string.charAt(i) == 'E')
e_count++;
else if (input_string.charAt(i) == 'i' || input_string.charAt(i) == 'I')
i_count++;
else if (input_string.charAt(i) == 'o' || input_string.charAt(i) == 'O')
o_count++;
else if (input_string.charAt(i) == 'u' || input_string.charAt(i) == 'U')
u_count++;
i++;
String display_message1 = input_string // 7. display the String
+ "\n\n" + "has " + input_string.length() + " characters.\n\n" // 8. display the number of characters
+ "There are \n"
+ a_count + " a's,\n" // 9. disaply the number of each vowel
+ e_count + " e's,\n"
+ i_count + " i's,\n"
+ o_count + " o's, and\n"
+ u_count + " u's.\n\n";
JOptionPane.showMessageDialog(null, display_message1, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);
yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
} while (i < input_string.length());
if (i == input_string.length())
{
yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
if (yes == 1)
{
input_string = JOptionPane.showInputDialog("Enter the sentence to search");
}
}
} // end of main
} // end of the class

In your code you have a condition where the loop can still be executed if yes is 0. Since yes is never redefined from what I can see, you basically have an infinite loop and your code will error out when i exits the bounds of your string's length.
Also not sure why you have two JOptionPanes at the bottom of the loop (which would execute x times where x = input_string.length())
Consider something like:
if(i == input_string.length()) {
//ask the user if they want to enter another string
if(the user selected yes){
yes = 1;
//instantiate again with new input_string
}
}
Another note: Assuming you want to show a message asking if the user wants to enter another string once you've finished iterating through their first entry, it seems moot to have the yes variable and condition.

Related

Have at least 5 valid names in Scan and introduce "end" to end the program - JAVA

My project is to ask the user to introduce up to 10 full names with up to 120 characters and at least two names with at least 4 characters. If the user reaches at least 5 valid names could introduce "end" to end the program, how do I would do it? (Note: The program needs to end if it reaches 10 names.)
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter up to 10 full names with up to 120 characters and at least two names with at least 4 characters:");
String fullName;
String[] SeparatedName;
int i = 0;
do {
fullName= keyboard.nextLine();
i++;
SeparatedName= fullName.split(" ");
//System.out.println(Arrays.toString(SeparatedName));
int l = 0;
for(int n = 0; n < SeparatedName.length; n++){
if(SeparatedName[n].length() >= 4 ) {
l++;
}
}
if(l >= 2 && fullName.length() <= 120 || fullName.equalsIgnoreCase("end") ) {
//valid name
System.out.println("'" +fullName+ "'" + " is valid");
}
else {System.out.println("'" +fullName+ "'" + " is invalid");}
}
while(!fullName.equalsIgnoreCase("end") || i<10);
keyboard.close();
}
Output (doesnt end):
aaaa aaaa
'aaaa aaaa' is valid
aaa aa
'aaa aa' is invalid
aaaa aaaa
'aaaa aaaa' is valid
aaaa aaaa
'aaaa aaaa' is valid
aaaaaaa aaaaaa
'aaaaaaa aaaaaa' is valid
end
'end' is valid
When the user introduced end should stop because it has already 5 valid names. If it reaches 10 full names should stop and it doesn't.
The problem is that you are not exiting the main method when your exit requirements are met. You can exit a method by using the return; keyword.
So add a if statement before the condition to the Do-While and change the loop condition to true, like this:
if(fullName.equalsIgnoreCase("end") || i>=10){
keyboard.close();
return;
}
while(true);
This way your method will exit when the exit requirements are met.
In the place of
if(l >= 2 && fullName.length() <= 120 || fullName.equalsIgnoreCase("end") ) {
//valid name
System.out.println("'" +fullName+ "'" + " is valid");
}
else {System.out.println("'" +fullName+ "'" + " is invalid");}
condition in your code, I think the following if-elseif-else condition addresses your needs better
if (fullName.equalsIgnoreCase("end")) {
break; // exits the do while loop
} else if (l >= 2 && fullName.length() <= 120 ) {
//valid name
System.out.println("'" +fullName+ "'" + " is valid");
} else {
System.out.println("'" +fullName+ "'" + " is invalid");
}

Trying to create a quiz with java, but something went wrong. What part of my program did i screw up?

So I'm starting to get the hang of java, and I'm creating a quiz as a mini project. However, when I get to the input part of my program, it breaks down. What's going on?
I also apologize for the formatting
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int score = 0;
int total = 0;
System.out.println("Are you ready for a quiz? (Y/N)");
char answer = in.findInLine(".").charAt(0);
if (answer == 'Y' || answer == 'y');
{
String a = "Barrow";
String b = "Juneau";
String c = "Anchorage";
String d = "Annapolis";
System.out.println("Alright! Lets get right to it!");
System.out.println("What is the Capital of Alaska?");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
char choice = in.findInLine(".").charAt(0);
if (choice == 'B' || choice == 'b')
{
System.out.println("Good Job! 1 point for you!");
score = score + 1;
}
else
{
System.out.println("Incorrect! the answer was actually " + b);
}
String e = "Yes";
String f = "No";
System.out.println("Alright, Next Question! Can you"
+ " store the value 'cat' in a variable of type int?");
System.out.println("A: " + e);
System.out.println("B: " + f);
char secchoice = in.findInLine(".").charAt(0);
if (secchoice == 'A' || secchoice == 'a')
{
System.out.println("Correct! Good Job!");
score = score + 1;
}
else
{
System.out.println("Incorrect");
}
System.out.println("What is the result of 2+2X3-5?");
int result = in.nextInt();
if (result == 3)
{
System.out.println("Correct! Good Job!");
}
else
{
System.out.println("Incorrect");
}
System.out.println("Your total score was " + score + "out of 3");
}
}
}
You are getting a NullPointerException on line 26 because of the way that findInLine() works. Basically, you have used up the one line of input you give it when it starts and the Scanner has advanced passed it to find the next one (which does not exist). In other words, you should use another method for Scanner or use an entirely different approach for getting input.
For example, it is preferable to use this technique
char answer = in.nextLine().charAt(0);
because nextLine() will wait until it has more input.
Of course, you will have to come up with some way to parse the input from the user to make sure that it is valid (i.e. if they can only choose between 'Y' and 'N' you handle the case where they choose neither).
That would look something like
char answer = parseInput(in.nextLine().charAt(0));
where parseInput(String s) is a method you write yourself.
As far as other approaches go, this tutorial from Oracle can help you get started.

Hangman stats error

My code does not show the number of wins, losses and numberOfGames I had played.
I've been trying to fix it for the last month and I'm going nowhere!
import java.util.Random;
import java.util.Scanner;
public class HangmanP2 {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String first, reverse = "";
String second, reverse2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Hangman!");
System.out.println("Enter your first name.");
first = in.nextLine();
System.out.println("Enter your last name to play.");
second = in.nextLine();
int length = first.length();
int length2 = second.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + first.charAt(i);
reverse = reverse.substring(0,1).toUpperCase() + reverse.substring(1).toLowerCase();
for ( int i = length2 - 1 ; i >= 0 ; i-- )
reverse2 = reverse2 + second.charAt(i);
reverse2 = reverse2.substring(0,1).toUpperCase() + reverse2.substring(1).toLowerCase();
System.out.println("Your name entered in reverse is: "+reverse+" "+reverse2);
startGame(reverse,reverse2);
}
public static void startGame(String reverse,String reverse2){
Random rnd = new Random ();
Scanner user = new Scanner (System.in);
String guess = "";
String message = "";
int count = 1;
boolean quit = false;
String fullWord = "";
int wins=0;
int loss=0;
int numberOfGames=0;
int guessC = 5;
String usedLetters ="";
String remainingLetters ="";
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int hinter = 0;
int z = rnd.nextInt(10);
int k = rnd.nextInt(2);
String words[][] = {{"earth","stars","light",
"world","about","again",
"stars","light","music",
"happy","water","amber",
"apple","piano","green",
"mouth","suger","stone",
"japan","china","after","lemon",
"grand",
"lives","twice","print"},{"smile",
"puppy","latin","vegan","phone","april",
"south","house","hangs","woman",
"power","today","india","night","candy",
"forum","birth","other","chris","irish",
"paste","queen","grace","crazy","plant",
"knife","spike","darth","vader","eagle",
"egypt","range","fists","fight","glory",
"March","smart","magic","codes","rolls",
"match","honor","glass","board","teams",
"bully","zebra","under","mango","brain",
"dirty","eight","zeros","train","cycle",
"break","necks","terms","slide","large"},{"stake","guess","wrong","anime","stick","outer","input"},{ "thing","write","white","black"}};
//Prints info of the game and topic that as been selected
System.out.println("Welcome to Hangman"+" "+reverse+" "+reverse2);
//This prints the '-' and spaces for the first run of the game only
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
//Nothing will change, this prints information to the user about his current status in-game.
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
//The loop that will continuously run the game, until the user fails or does not want to play again.
do{
//The following variable's make sure there is not stacking from previous data when the loop runs again.
remainingLetters = "";
count = 0;
//Ask the user for a letter to guess
System.out.println("\nEnter a letter to guess the word): ");
guess = user.nextLine();
//The following for-loop converts ASCII table [A-Z] to actually characters and if the player used a letter it will not show up or add to the string each run of the do-loop.
for(int x = 65; x < 91;x++){
Character current = new Character ((char)x);
String current2 = current.toString();
if(!usedLetters.contains(current2)){
remainingLetters += current;
}
}
//Converts the user's first character to a string which is converted into another character and again converted into a String (Seem's useless) but i used it this way cause i was getting an error.
Character convert = new Character (guess.charAt(0));
Character conv = new Character (convert);
String converted = convert.toString();
//The letters the player uses will be added to a string, if it has not already been added and only if it is a letter.
if(!usedLetters.contains(converted) && conv.isLetter(convert)){
usedLetters+=guess.charAt(0);
}
//Inside this for-loop it turns our word into a String and the user's first character into a string.
for(int index = 0; index < words[z][k].length();index++){
//This is a helper
count++;
//Conversion of variables
Character current2 = new Character ( words[z][k].charAt(index));
String current = current2.toString();
Character current3 = new Character (guess.charAt(0));
String current4 = current3.toString();
String current5 = current4.toUpperCase();
String current6 = words[z][k].toUpperCase();
//If the players gets a letter correct, do the following.
if(current4.equalsIgnoreCase(current))
{
//Add's on to the previous string from where the player got it correct and change it to the correct letter instead of a '-'.
message = message.substring(0,index) + guess + message.substring(index + 1);
}
//If the player gets it wrong and the helper variable is equal to 1 (so that it does not follow the loop of the for-loop and it is not one of the special characters in the game('!' or '?').
if(!current6.contains(current5) && count == 1 && guess.charAt(0) != '?' && guess.charAt(0) != '!'){
guessC--;
}
}
//Prints information to the user of their current topic
//The secret word the player has to guess
System.out.println("Secret word: \t\t" + message.toUpperCase());
//The letters in the alphabet that have not been used yet
System.out.print("\nLetters remaining: ");
System.out.print(remainingLetters.toUpperCase() + "\n\n");
//This will print a message to the user, telling them information on using a hint or the hint itself.
//Letters the user has used since the game session has been running
System.out.print("\nLetters Used: ");
System.out.print(usedLetters.toUpperCase() + "\n");
//The amount of guesses the player has left
System.out.println("\nGuesses Remaining: " +guessC );
//If the player enters a '?' it will do the following.
if(guess.charAt(0) == '?'){
if(hinter <2){
//Displays what is in the array and information about the delay, while losing guesses.
hinter++;
System.out.print("\nHint will appear after next guess! \n");
guessC -=2;
}
}
//If the user guesses the word correct
if(message.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user ask to guess the entire word it is stored in a separate variable and make quit equal to true.
if(guess.charAt(0) == '!')
{
System.out.print("\nEnter the secret word: ");
fullWord = user.nextLine();
//if the user guesses the word correct then it will tell the user they are correct and make quit equal to true.
if(fullWord.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user does not get it right it will tell the user they are wrong and make quit equal to true.
else{
System.out.println("YOU ARE INCORRECT! the word is: " + words[z][k] + " ");
loss++;
quit = true;
}
}
//If the guesses counter equal 0 then it will tell them that they have lost and make quit equal to true.
if(guessC == 0){
System.out.println("GAME OVER! The secret word was [ " + words[z][k] + " ]!");
loss++;
quit = true;
}
//This is what happens when quit eventually becomes true, the user is asked if they would like to play again.
if(quit == true){
System.out.println("\nWould you like to play again (Y or quit)? ");
System.out.println("\nOr type [stats] to check your work");
guess = user.nextLine();
//If they do want to play again, they will need to enter Y and if they do it will give them another word to guess and resets there information so that there will be no overlap.
if(guess.equalsIgnoreCase("Y")){
quit = false;
z = rnd.nextInt(10);
k = rnd.nextInt(2);
guess = " ";
guessC = 6;
message = "";
usedLetters = "";
hinter = 0;
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
}
if(guess.equals("stats")){
printGameStats(wins,loss,numberOfGames);
}
else{
//If the user enters 'N' then they will be told the following and the scanner will be closed.
System.out.println("THANK YOU FOR PLAYING HAVE A GOOD DAY!");
user.close();
}
}
//end of the while loop which will only stop if quit equals true.
}while(quit != true );
}
private static void printGameStats(int wins,int loss,int numberOfGames) {
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
// Print titles
System.out.printf("| %6s | %6s | %12s |\n",
"WINS", "LOSSES", "GAMES PLAYED");
// Line
System.out.print("|");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(16);
System.out.print("+");
printDashes(18);
System.out.println("|");
// Print values
System.out.printf("| %6d | %6d | %12d |\n",
wins, loss, numberOfGames);
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
}
private static void printDashes(int numberOfDashes) {
for (int i = 0; i < numberOfDashes; i++) {
System.out.print("-");
}
}
}

determining logic error that causes a misprint

So, I am pretty new to java and I wanted to try my hand at debugging in command line, namely using jdb on a code that has a couple errors. I was tinkering with this code:
import java.util.Scanner;
import java.io.File;
class LetterHome{
static final int MAX_CODE = 5;
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(new File(args[0]));
String phrase;
int sentenceCode, modifierCode;
System.out.println("Dear Mom and Dad:\n");
while( in.hasNext() ){
sentenceCode = in.nextInt();
modifierCode = in.nextInt();
if( (sentenceCode < 1) || (sentenceCode >= MAX_CODE) ) {
System.out.println(sentenceCode + " is not a valid sentence code");
continue;
}
if( sentenceCode == 1 ){
if( modifierCode == 1 ){
phrase = "great";
}else if( modifierCode == 2 ){
phrase = "ok";
}else{
phrase = "ERROR";
}
System.out.println("My classes are going " + phrase + ".");
}else if( sentenceCode == 2 ){
phrase = weatherModifier(modifierCode);
System.out.println("The weather here has been " + phrase + ".");
}else if( sentenceCode == 3 ){
if( modifierCode == 1 ){
phrase = "after the quarter ends";
}else if( modifierCode == 2 ){
phrase = "in a few weeks";
}else if( modifierCode == 3 ){
phrase = "next weekend";
}else{
phrase = "ERROR";
}
System.out.println("I plan to come home for a visit " + phrase + ".");
}else if( sentenceCode == 4 ){
System.out.println("Do you think you could send me $" + modifierCode + "?");
System.out.println("I have to buy another book for one of my classes.");
}else if( sentenceCode == 5 ){
if( modifierCode == 1 ){
phrase = "cookies";
}else if( modifierCode == 2 ){
phrase = "stuff";
}else; if( modifierCode == 3 ){
phrase = "money";
}else{
phrase = "ERROR";
}
System.out.println("Thanks for the " + phrase + " you sent.");
}
}
}
static String weatherModifier(int m) {
String word=null;
if(m == 1)
word = "great";
if(m == 2)
word = "foggy";
if(m == 3)
word = "hot";
if(m == 4)
word = "cold";
if(m == 5)
word = "variable";
if( m<1 && m>5)
word = "ERROR";
return word;
}
}
And I've already found a ";" that was out of place. I know that something is off with the values assigned to the terms in the end (I think), because when I compile the program, I get this output:
Dear Mom and Dad:
//
// 5 is not a valid sentence code
// My classes are going great.
// The weather here has been foggy.
// I plan to come home for a visit in a few weeks.
Instead of classes going "great", I get "foggy", which I noticed when I ran jdb. I ran the code with this data file:
5 2
1 1
2 1
3 2
The code itself prints a template with possible options outlined in the data file, which you may have already noticed. Here's the full list of possibilities:
// 1. My classes are going _____.
// 1. great
// 2. ok
// 2. The weather here has been _____.
// 1. great
// 2. foggy
// 3. hot
// 4. cold
// 5. variable
// 3. I plan to come home for a visit _____.
// 1. after the quarter ends
// 2. in a few weeks
// 3. next weekend
// 4. Do you think you could send me $_____?
// I have to buy another book for one of my classes.
// 5. Thanks for the _____ you sent.
// 1. cookies
// 2. stuff
// 3. money
However, I'm not sure what's off about the logic in the code. Any tips? Please let me know if I need to make some clarification. Thanks.
You added an extra ;at the end of if (m==2); in your weatherModifier function. Remove it!
I figured out the issue, actually:
It was in " if( (sentenceCode < 1) || (sentenceCode >= MAX_CODE) )"
I had to change ">=" to ">"

Cannot accurately asses Strings

I wrote some code that is supposed to ask for input from the user and assign it to the String skillAssign. When I try to asses skillAssign, it returns false no matter what. Here is my code:
import java.util.*;
public class CharacterCustomization
{
public CharacterCustomization()
{
}
public static void Customization()
{
Scanner keyboard = new Scanner(System.in);
int skillPoints = 100;
String skillAssign = "";
int newMaxHealth = 0;
int newMaxMagic = 0;
int newMaxStamina = 0;
int assignmentValue = 0;
boolean isDone = false;
System.out.println("Welcome to character customization, you have 100 points to allocate to your skills.");
System.out.println("To allocate points, type name of skill, followed by the points you want to assign (blank for positive, - for negative, ex. -5)");
System.out.println("Put Skill on one line, and press enter, then the value on the next line");
System.out.println("Type \"stats\" to view full stats at any time");
System.out.println("Type \"done\" to finish");
while (true)
{
while (isDone == false)
{
skillAssign = keyboard.nextLine();
if (skillPoints == 0)
{
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
System.out.println("Type \"done\"to finish");
}
if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
{
assignmentValue = keyboard.nextInt();
if (((skillAssign.equals("health")) || (skillAssign.equals("Health"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxHealth = (assignmentValue + newMaxHealth);
}
else if (((skillAssign.equals("magic")) || (skillAssign.equals("Magic"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxMagic = (assignmentValue + newMaxMagic);
}
else if (((skillAssign.equals("stamina")) || (skillAssign.equals("Stamina"))) && (skillPoints - assignmentValue >=0))
{
skillPoints = (skillPoints - assignmentValue);
newMaxStamina = (assignmentValue + newMaxStamina);
}
else
{
//System.out.println("Sorry, I could not read that!");
System.out.println(skillAssign == "stats");
}
}
else if (skillAssign.equals("stats"))
{
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
}
else if ((skillAssign.equals("done")) || (skillAssign.equals("Done")))
{
isDone = true;
continue;
}
else
{
System.out.println("Sorry, I could not read that!");
}
}
System.out.println("Are you sure this is the setup you want? [y] [n]");
System.out.println("Max Health: " + newMaxHealth);
System.out.println("Max Magic: " + newMaxMagic);
System.out.println("Max Stamina: " + newMaxStamina);
System.out.println("Skill points left: " + skillPoints);
//skillAssign = keyboard.nextLine();
if (((keyboard.nextLine()).equals("y")) || ((keyboard.nextLine()).equals("Y")) || ((keyboard.nextLine()).equals("yes")) || ((keyboard.nextLine()).equals("Yes")))
{
Player player = new Player(newMaxHealth, newMaxMagic, newMaxStamina);
}
else
{
isDone = false;
}
}
}
}
Its not complete, but Im inputting stats when prompted and all evaluations of it are false
Is there a way I can get it to read the variable properly?
You will always get in inside this condition scope if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
It because that when one word failed to pass it, the other condition will let it pass, because they are different completely.
e.g:
let's take "stats", this will results with if (false || true) => true.
let's take "done", this will results with if (true || false) => true.
let's take "sTats", this will results with if (true || true) => true.
You can't escape it, you need to check it like that:
if (!(skillAssign.equals("stats") || skillAssign.equals("done")))
this way we're checking if either of the logical expression are true, then we change it to "not" and then checking if the whole condition is true.
P.S
A. You can use "abc".equalsIgnoreCase("AbC") instead what you're using now.
B. Don't add for every logical expression parenthesis it's making the code more complex and unclear for the first glance.
The problem was that I was using || instead of && in the if ((!(skillAssign.equals("stats"))) || (!(skillAssign.equals("done"))))
What ever Orel said is pretty much it. Just wanna add if you are using System.out.println(skillAssign == "stats") to asses your skillAssign it will always return false, even if they have the same value.
Because == compare the reference of Strings not their values.
you must use equals() method.

Categories