Verifying strings Java - java

do {
grade[y] = JOptionPane.showInputDialog(null, "For student #" + inputGrades.students + " enter grade for course #" + classes);
if (!grade[y].equals("A") || !grade[y].equals("B") || !grade[y].equals("C") || !grade[y].equals("D") || !grade[y].equals("F")) {
grade[y] = JOptionPane.showInputDialog(null, "For student #" + inputGrades.students + " enter grade for course #" + classes);
} else {
validgrade = true;
}
} while (!validgrade);
I'm trying to make a sure a sting equals either A, B, C, D, or F. I get stuck in an infinite loop. Why?

This condition is always true:
if (!grade[y].equals("A") || !grade[y].equals("B") || !grade[y].equals("C") || !grade[y].equals("D") || !grade[y].equals("F"))
grade[y] cannot equal A, B, C, D, and F at the same time. At most one !equals(...) will be false. The remaining four would be true, turning the results of OR into true as well.
You need && instead of ||:
if (!grade[y].equals("A") && !grade[y].equals("B") && !grade[y].equals("C") && !grade[y].equals("D") && !grade[y].equals("F"))
In addition, it is not necessary to call JOptionPane.showInputDialog inside the if conditional. All you need to do is letting the loop continue. So the simplified code could look like this:
do {
grade[y] = JOptionPane.showInputDialog(null, "For student #" + inputGrades.students + " enter grade for course #" + classes);
} while (!grade[y].equals("A") && !grade[y].equals("B") && !grade[y].equals("C") && !grade[y].equals("D") && !grade[y].equals("F"));

Related

Why is my program entering a while loop when the condition is false?

When I input a string operator whether it be addition(+), subtraction(-), multiplication(*), division(/) or module(%), it still enters the while loop even when I enter a valid input. I don't know what the problem could be because the while loop is working fine where I have to enter an int-value for variable num2.
import java.util.Scanner;
public class PolishNotationCalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1;
int num2;
String operator;
System.out.println("Polish notation calculator");
System.out.print("Please enter an operation(+, -, *, /, %) ");
operator = input.nextLine();
while (!operator.equals("+") || !operator.equals("-") || !operator.equals("*") || !operator.equals("/") || !operator.equals("%")) {
System.out.println("Please enter a valid operation ");
operator = input.nextLine();
if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%"))
break;
}
System.out.print("");
System.out.print("Please enter the first number ");
num1 = input.nextInt();
System.out.print("Please enter the second number ");
num2 = input.nextInt();
while (num2 == 0 && operator.equals("/")) {
System.out.println("Please pick a non zero number: ");
num2 = input.nextInt();
}
while (num2 == 0 && operator.equals("%")) {
System.out.println("Please pick a non zero number: ");
num2 = input.nextInt();
}
if (operator.equals("+"))
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
else if (operator.equals("-"))
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
else if (operator.equals("*"))
System.out.println(num1 + " * " + +num2 + " = " + (num1 * num2));
else if (operator.equals("/"))
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
else if (operator.equals("%"))
System.out.println(num1 + " % " + num2 + " = " + (num1 % num2));
}
}
if you write your boolean selection in english it reads "While the operator does not equal "+" or it does not equal "-" or it does not equal "/" or it does not equal "*" or it does not equal "%" do the loop.
You need it to say "While the operator does not equal "+" AND it does not equal "-" AND it does not equal "/" AND it does not equal "*" AND it does not equal "%" do the loop.
Change || to && and it should work
For a while loop to be enacted all the parameters need to be true. So if one of the parameters is false, the while loop does not activate.
operator is always not equal to at least one of these strings: e.g. if it is equal to +, then it's not equal to -. If you combine one or more true conditions with ||, the overall result will be true.
You need to use && instead of ||, so that the loop breaks if any one of the conditions match:
while (!operator.equals("+") && !operator.equals("-") && ... ) {
You then don't need to check the value of operator again inside the loop; just let the new loop guard check it and break.
A more syntactically concise alternative would be to use a collection:
List<String> allowedOperators = Arrays.asList("+", "-", "*", "/", "%");
while (!allowedOperators.contains(operator)) {
System.out.println("Please enter a valid operation ");
operator = input.nextLine();
}
Similarly, when you are checking for num2 == 0:
List<String> zeroDenominatorOps = Arrays.asList("/", "%");
if (zeroDenominatorOps.contains(operator)) {
while (num2 == 0) {
// ...
}
}
while (!operator.equals("+") || !operator.equals("-") || !operator.equals("*") || !operator.equals("/") || !operator.equals("%")) {
System.out.println("Please enter a valid operation ");
operator = input.nextLine();
if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%"))
break;
}
For example when you enter "+" it becomes while(false || true|| true || true). so it always goes into while loop
You should substitute the || (or) with && (and)
SO
while (!operator.equals("+") || !operator.equals("-") || !operator.equals("*") || !operator.equals("/") || !operator.equals("%")) {
Becames
while (!operator.equals("+") && !operator.equals("-") && !operator.equals("*") && !operator.equals("/") && !operator.equals("%")) {
EDIT
You need an AND not an OR.
Lets say you input "+",which is a valid operator.
You'll enter the while because "+" NOT EQUALS "-", your second condition. This because the while conditions are in OR.
If you put these conditions in AND (&&), the "+" does not enter the while because one of the conditions is not true ( !operator.equals("+") )
Try this by changing ! to the whole parameters inside the while loop,It will start working
while (!(operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%"))) {
System.out.println("Please enter a valid operation ");
operator = input.nextLine();
if ((operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%")))
break;
}
It's simple math that sometimes people just forgets.
Lets simplify the cases.
1 OR x = 1;
1 AND x = x;
Lets be more concrete. Let we have some variable, A, B and C.
In the first case, OR, we have:
Which means that if at least one is true, the all expression is true. In you case having one operation that does not appear means that the loop must be true. Therefore, you should put something like this:
Which means not A AND not B AND not C.
I hope I have helped.
Have a nice day. :)
The loop condition has a different meaning than you thought. It's always true for any input string. It's the kind of condition that you will never have to write (hopefully).
To understand this better, let's first define when an operator can be accepted, in English:
An operator is accepted if it's one of the five operators: +, -, *, /, %
"One of" basically means "or". Therefore the corresponding code is
operator.equals("+") ||
operator.equals("-") ||
operator.equals("*") ||
operator.equals("/") ||
operator.equals("%")
And we can wrap it in a method:
private static boolean acceptable(String operator) {
return operator.equals("+") ||
operator.equals("-") ||
operator.equals("*") ||
operator.equals("/") ||
operator.equals("%");
}
Now the read-check-loop logic is very simple:
String operator;
do {
System.out.println("Please enter a valid operation ");
operator = input.nextLine();
} while (!acceptable(operator));
#SaclyrBarlonium, this is what I'm talking about. :P
Side Note
IMHO, every programmer should know De Morgan's laws so well that they can instinctively detect logical inconsistencies in the code. The inconsistency in this case is between the loop condition and the if statement in the loop body. If we put them side-by-side, we know that they are not equivalent, according to De Morgan's Law:
!operator.equals("+") || !operator.equals("-") || !operator.equals("*") || !operator.equals("/") || !operator.equals("%")
operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%")
But they should be equivalent, because the intent are the same: to continue the loop when the user entered a invalid operator and to terminate otherwise.

Second console prompt fails in Java

This is a class assignment where I have to get the user to input three names, then sort them alphabetically in descending or ascending order based again on user input.
I've got the input of the names down and managed to find a way to sort them but my code fails when I ask the user to choose between ascending and descending (ie: my following if statements don't execute). I'm sure it's a simple explanation but I haven't been able to figure out what I'm doing wrong.
Here's the code:
package javaapplication9;
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
String a = getInput("Enter the first name: ");
String b = getInput("Enter the second name: ");
String c = getInput("Enter the third name: ");
String ascending = getInput("Enter [A] for Ascending and [D]"
+ "for Descending order.");
// find first name alphabetically
String min = "";
if (a.compareTo(b) <= 0 && a.compareTo(c) <= 0)
{
min = a;
}
else if (b.compareTo(a) <= 0 && b.compareTo(c) <= 0)
{
min = b;
}
else if (c.compareTo(b) <= 0 && c.compareTo(a) <= 0)
{
min = c;
}
// find middle name alphabetically (and by descending order)
String middle = "";
if (a.compareTo(b)*a.compareTo(c) <= 0)
{
middle = a;
}
else if (b.compareTo(a)*b.compareTo(c) <= 0)
{
middle = b;
}
else if (c.compareTo(b)*c.compareTo(a) <= 0)
{
middle = c;
}
// find last name alphabetically
String last = "";
if (a.compareTo(b) >= 0 && a.compareTo(c) >= 0)
{
last = a;
}
else if (b.compareTo(a) >= 0 && b.compareTo(c) >= 0)
{
last = b;
}
else if (c.compareTo(b) >= 0 && c.compareTo(a) >= 0)
{
last = c;
}
// This is where I am having difficulty. This part of the program
// never executes when I run the file and I can't seem to figure
// out why.
if (ascending == "a")
{
System.out.println(min + " " + middle + " " + last);
}
if (ascending == "d")
{
System.out.println(last + " " + middle + " " + min);
}
} // end main function
private static String getInput(String prompt)
{
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
}
To properly compare strings in Java you need to use the equals(String compare) method of the String class.
Because you tell the user to enter uppercase letters, use the equalsIgnoreCase method instead:
if(ascending.equalsIgnoreCase("a")) {
System.out.println(min + " " + mid + " " + last);
}
When comparing strings, use .equals(), not ==.
Use this:
if (ascending.equals("a")){
instead of:
if (ascending == "a")
Full Code:
if (ascending.equals("a"))
{
System.out.println(min + " " + middle + " " + last);
}
if (ascending.equals("d"))
{
System.out.println(last + " " + middle + " " + min);
}

While loop one condition always returning true?

I am trying to make a conditional statement with two "ifs", and it works when I input the correct thing, but when I input an incorrect pokemon and a correct level it still works. I am pretty sure that one of the conditions in my while statement is always true (the first part). Here is the code (sorry about the formatting, just know that it is all formatted correctly in the Java environment):
while ((!(Pokemon.equalsIgnoreCase(Pikachu)) || !(Pokemon.equalsIgnoreCase(Charmander)) || !(Pokemon.equalsIgnoreCase(Squirtle)) || !(Pokemon.equalsIgnoreCase(Bulbasaur))) && !((Level <= 15)&&(Level >= 1 ))) {
System.out.println();
System.out.println("Which one would you like? What level should it be?\n1 to 15 would be best, I think.");
Pokemon = sc.next();
Level = sc.nextInt();
if ((Level <= 15) && (Level >= 1)) {
if ((Pokemon.equalsIgnoreCase(Pikachu)) || (Pokemon.equalsIgnoreCase(Charmander)) || (Pokemon.equalsIgnoreCase(Squirtle)) || (Pokemon.equalsIgnoreCase(Bulbasaur))) {
System.out.print("Added level " + Level + " " + Pokemon + " for " + Trainer + ".");
}
else {
System.out.println("Invalid Pokemon!");
}
}
else {
System.out.println("Invalid Level!");
}
}
Pokeman will always be either not X or not Y, it's basic logic since if it's X, then not-Y is true. If it's Y, then not-X is true. If it's neither then both will be true.
Change || to && and think through your logic on paper.
Should be:
while ((!(Pokemon.equalsIgnoreCase(Pikachu)) &&
!(Pokemon.equalsIgnoreCase(Charmander)) &&
!(Pokemon.equalsIgnoreCase(Squirtle)) &&
!(Pokemon.equalsIgnoreCase(Bulbasaur))) &&
!((Level <= 15)&&(Level >= 1 )))

Java String Index Out of Bound ( String Index out of Range) on line 150

Hi I'm a newbie with Java, and I'm trying to write a small simple text-base quiz game for one of my homework, this here is the code:
import java.util.* ;
class Quiz
{
public static void main( String[] not_in_use )
{
Scanner keyboard = new Scanner( System.in ) ;
int money = 0;
char answer;
boolean quit = false;
int id = 0;
int id1 = 0;
System.out.print("\nWelcome to Haluatko Miljonääriksi?."
+ "\nAn interactive quiz game about Finland by Khoa \"Kazkyu\" Nguyen.\n"
+ "\nYou are given 15 multiple-choice questions."
+ "\nEarn money and move on by choosing the right answer, final price is 1 million Euros."
+ "\nAnswer a question by typing A, B, C, D on your keyboard."
+ "\nType in \"save\" to use Lifesaver."
+ "\nQuit the game and keep your earned money by typing \"exit\"."
+ "\nYou still win with half the money you earned if you answer wrong."
+ "\n\nPress Enter to begin: ");
keyboard.nextLine();
if ( (id <= 15) && (quit == false))
{
System.out.print("\nWhat is the name of Finland in Finnish?:\n"
+"\nA. Suomi"
+"\nB. Soumi"
+"\nC. Suomea"
+"\nD. Soumea"
+"\n\n");
answer = keyboard.nextLine().charAt(0);
while (!( ( answer == 'A' ) ||
( answer == 'a' ) || ( answer == 'B' ) ||
( answer == 'b' ) || ( answer == 'C' ) ||
( answer == 'c' ) || ( answer == 'D' ) ||
( answer == 'd' ) || ( answer == 'E' ) ||
( answer == 'e' ) || ( answer == 'S' ) || (answer == 's')))
{
System.out.print( "\nWrong input A,B,C,D or Exit or Save only.\n");
answer = keyboard.nextLine().charAt( 0 ) ;
}
if (( answer == 'A') || (answer == 'a'))
{
money = money + 200;
id = id + 1;
System.out.print ( "\nCorrected, you earned " + money + " Euros\n" );
}
else if (( answer == 'B') || (answer == 'b') || (answer == 'C') || (answer == 'c')
|| ( answer == 'D') || (answer == 'd'))
{
System.out.print ( "\nWrong, you lose, no money for you\n"
+"Game over, good luck next time\n");
quit = true;
}
else if ((answer == 'E') || (answer == 'e'))
{
System.out.print ("\nYou choose to quit, your money is: " + money + " Euros"
+"\nGood luck next time\n");
quit = true;
}
else if ((answer == 'S') || (answer == 's'))
{
id1 = id1 + 1;
System.out.print ("\nPlease choose your life saver:"
+"\nType 1 for \"Skip and get point\""
+"\nType 2 for \"Surf Wikipedia for answer\", Warning: Very Random"
+"\nType 3 for \"Asked Jere, Michal, Jaska, Marios for help\", Warning: Very Random"
+"\n\n");
int choice = keyboard.nextInt();
if (choice == 1)
{
money = money + 200;
id = id + 1;
answer
System.out.print ("\nQuestion Skipped, earn " + money + " Euros.\n");
}
if ( choice == 2 )
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if (randomNum == 1)
{
money = money + 200;
System.out.print ("\nWiki said answer is A, right answer, ");
}
else if (randomNum == 2)
{
System.out.print ("\nWiki said answer is B ,wrong answer, Game over.\n"
+"You earned " + money + " Euros.\n");
quit = true;
}
else if (randomNum == 3)
{
System.out.print ("\nWiki said answer is C ,wrong answer, Game over.\n"
+"You earned " + money + " Euros.\n");
quit = true;
}
else if (randomNum == 4)
{
System.out.print ("\nWiki said answer is D ,wrong answer, Game over.\n"
+"You earned " + money + " Euros.\n");
quit = true;
}
}
if (choice == 3)
{
Random rand1 = new Random();
int randomNum1 = rand1.nextInt((4 - 1) + 1) + 1;
if (randomNum1 == 1)
{
money = money + 200;
System.out.print ("\nYou asked Jere and got the answer: A.\n"
+"Right answer, " + money + " Euros.\n");
}
if (randomNum1 == 2)
{
money = money + 200;
System.out.print ("\nYou asked Michal and got the answer: A.\n"
+"Right answer, " + money + " Euros.\n");
}
if ( randomNum1 == 3)
{
System.out.print ("\nYou called Jaska and recieved a \"Whatever, I like milk, why not\" for an answer."
+ "\nYou answered \"Whatever, I like milk, why not\", Wrong answer."
+ "\nGame over, You earn " + money + " Euro.\n");
quit = true;
}
if ( randomNum1 == 4)
{
System.out.print ("You called Marios and he gave you this answer:\n"
+ "\nAyy Lmao, get rekt m8, inb4 4chan raid."
+ "\nYou don't know what the fuck it mean."
+ "\nSo you quit with " + money + " Euros in your pocket.\n");
quit = true;
}
}
}
}
if ( (id <= 15) && (quit == false))
{
System.out.print("\nWhen is the Finnish's Independence Day?:\n"
+"\nA. 12th of December"
+"\nB. 25th of December"
+"\nC. 6th of December"
+"\nD. 31th of December"
+"\n\n");
****\\line 150 THIS IS LINE 150 WHERE IT HAPPEN\\
answer = keyboard.nextLine().charAt(0);****
while (!( ( answer == 'A' ) ||
( answer == 'a' ) || ( answer == 'B' ) ||
( answer == 'b' ) || ( answer == 'C' ) ||
( answer == 'c' ) || ( answer == 'D' ) ||
( answer == 'd' ) || ( answer == 'E' ) ||
( answer == 'e' ) || ( answer == 'S' ) || (answer == 's')))
{
System.out.print( "\nWrong input A,B,C,D or Exit or Save only.\n");
answer = keyboard.nextLine().charAt( 0 ) ;
}
if (( answer == 'C') || (answer == 'c'))
{
money = money + 250;
id = id + 1;
System.out.print ( "\nCorrected, you earned " + money + " Euros\n" );
}
else if (( answer == 'B') || (answer == 'b') || (answer == 'A') || (answer == 'a')
|| ( answer == 'D') || (answer == 'd'))
{
money = money / 2;
System.out.print ( "\nWrong, you lose, your money is " + money + " Euros\n"
+"Game over, good luck next time\n");
quit = true;
}
else if ((answer == 'E') || (answer == 'e'))
{
System.out.print ("\nYou choose to quit, your money is: " + money + " Euros"
+"\nGood luck next time\n");
quit = true;
}
else if ((answer == 'S') || (answer == 's'))
{
id1 = id1 + 1;
System.out.print ("\nPlease choose your life saver:"
+"\nType 1 for \"Skip and get point\""
+"\nType 2 for \"Surf Wikipedia for answer\", Warning: Very Random"
+"\nType 3 for \"Asked Jere, Michal, Jaska, Marios for help\", Warning: Very Random"
+"\n\n");
int choice = keyboard.nextInt();
if (choice == 1)
{
money = money + 250;
id = id + 1;
System.out.print ("\nQuestion Skipped, earn " + money + " Euros.\n");
}
if ( choice == 2 )
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if (randomNum == 1)
{
money = money + 250;
System.out.print ("\nWiki said answer is C, right answer, ");
}
else if (randomNum == 2)
{
System.out.print ("\nWiki said answer is B ,wrong answer, Game over.\n"
+"You earned " + money + " Euros.\n");
quit = true;
}
else if (randomNum == 3)
{
System.out.print ("\nWiki said answer is A ,wrong answer, Game over.\n"
+"You earned " + money + " Euros.\n");
quit = true;
}
else if (randomNum == 4)
{
System.out.print ("\nWiki said answer is D ,wrong answer, Game over.\n"
+"You earned " + money + "Euros.\n");
quit = true;
}
}
if (choice == 3)
{
Random rand1 = new Random();
int randomNum1 = rand1.nextInt((4 - 1) + 1) + 1;
if (randomNum1 == 1)
{
money = money + 200;
System.out.print ("\nYou asked Jere and got the answer: C.\n"
+"Right answer, " + money + " Euros.\n");
}
if (randomNum1 == 2)
{
money = money + 200;
System.out.print ("\nYou asked Michal and got the answer: C.\n"
+"Right answer, " + money + " Euros.\n");
}
if ( randomNum1 == 3)
{
System.out.print ("\nYou called Jaska and recieved a \"Whatever, I like milk, why not\" for an answer."
+ "\nYou answered \"Whatever, I like milk, why not\", Wrong answer."
+ "\nGame over, You earn " + money + " Euro.\n");
quit = true;
}
if ( randomNum1 == 4)
{
System.out.print ("You called Marios and he gave you this answer:\n"
+ "\nAyy Lmao, get rekt m8, inb4 4chan raid."
+ "\nYou don't know what the fuck it mean."
+ "\nSo you quit with " + money + " Euros in your pocket.\n");
quit = true;
}
}
}
}
}
}
Everything seem to work fine except when I type in s to use the lifesaver, after choosing 1, it will skip the question like I want it to, but it also give me an Index out of bound error, and it say it's on line 150, I'm so confuse with this, everyother input work fine.
Please help me, thank you
If answer = keyboard.nextLine().charAt(0) throws a StringIndexOutOfBoundsException the only possibility is that keyboard.nextLine() returns an empty string.
The problem is that keyboard.nextLine() is an empty string, which is why it throws an exception.
The reason it is empty is because after reading the integer from the user, there is still a newline character in the buffer, which causes problems.
The easiest way to fix it (tested) is to get the integer from the user like so:
System.out.print("\nPlease choose your life saver:"
+"\nType 1 for \"Skip and get point\""
+"\nType 2 for \"Surf Wikipedia for answer\", Warning: Very Random"
+"\nType 3 for \"Asked Jere, Michal, Jaska, Marios for help\", Warning: Very Random"
+"\n\n");
//Modify this line right here like so.
int choice = Integer.parseInt(keyboard.nextLine());
This will stop the newline from being in the buffer, which solves all your problems.
keyboard.nextLine() returns an Empty string (a string with 0 characters - "".
You can check it by doing System.out.println(keyboard.nextLine().length());
When you use the livesaver, there is no keyboard input, so keyboard.nextLine() is just an empty String. Since it is empty, it has no char at index 0. You have to implement some logic that skips the scanning for keyborad input part when you use a livesaver.
in option 1 you have
answer
no semicolon or anything it should tell you this in your compliler i have no idea why it didn't, it bugs out after that naturaly.

String index out of bounds? (Java, substring loop)

This program I'm making for a COSC course isn't compiling right, I keep getting the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1765)
at VowelCount.main(VowelCount.java:13)
Here's my code:
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input, letter;
Scanner scan = new Scanner (System.in);
System.out.println ("Please enter a string: ");
input = scan.nextLine();
while (count <= input.length() ) {
letter = input.substring(count, (count + 1));
if (letter == "a") {
a++; }
if (letter == "e") {
e++; }
if (letter == "i") {
i++; }
if (letter == "o") {
o++; }
if (letter == "u") {
u++; }
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
To my knowledge this should work, but why doesn't it? Any help would be great. Thank you!
You may need to take out the = in the line
while (count <= input.length() ) {
and make it
while (count < input.length() ) {
because it is causing the substring to read beyond the length of the string.
===============
But I'll add a few extra bits of advice even though its not asked for:
do not use == to compare strings, use
letter.equals("a")
instead. Or even better, try using
char c = input.charAt(count);
to get the current character then compare like this:
c == 'a'
I think your loop condition should be count < input.length. Right now, the last iteration runs with count == length, so your substring call is given a start index after the last character in the string, which is illegal. These type of boundary errors are very common when writing such loops, so it's always good to double- and triple-check your loop conditions when you encounter a bug like this.
Also, comparing strings with the == operator usually won't do what you want. That compares whether or not the two variables reference the same object. Instead, you want to test string1.equals(string2), which compares the contents of the two strings.
Removing the equal sign should fix that.
while (count < input.length()) {
and since you want to get a single character, you should do this:
substr(count,1)
because the 2nd parameter is actually length, not index.
Fixed it with help from everyone, and especially Vincent. Thank you! Runs wonderfully.
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input;
char letter;
Scanner scan = new Scanner (System.in);
System.out.print ("Please enter a string: ");
input = scan.nextLine();
while (count < input.length() ) {
letter = input.charAt (count);
if (letter == 'a')
a++;
if (letter == 'e')
e++;
if (letter == 'i')
i++;
if (letter == 'o')
o++;
if (letter == 'u')
u++;
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
Before loop,try below
if(input.length()>0){
//you code
}

Categories

Resources