Fixed it. You have to create a new instance of Scanner every time you go through the loop (don't know why to be honest, but it worked).
- Code: Select all
package pg231num1;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean exclam = false;
boolean question = false;
String sentence;
boolean answer = false;
String reply;
do {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your question or concern: ");
sentence = keyboard.nextLine(); //stores input as string
switch (sentence.charAt(sentence.length() - 1))//checks for ! or ?
{
case '!' :
exclam = true;
break;
case '?' :
question = true;
break;
}
if ((sentence.length() % 2 == 0) && (question == true)){//checks to see if even and question
System.out.println("Yes");
}
else if ((sentence.length() % 2 != 0) && (question == true)){ //checks to see if odd and question
System.out.println("No");
}
else if (exclam == true){ //checks to see if !
System.out.println("Wow");
}
else if((question == false) && (exclam == false))//checks to see if neither ! or ? are present
{
System.out.println("You always say " + sentence);
}
System.out.println("Would you like to ask another question?");
System.out.println("Enter yes or no: ");
reply = keyboard.next();
if (reply.equalsIgnoreCase("yes")) {
answer = true; }
//System.out.println(sentence.charAt(length - 1)); //prints last char of sentence
} while (answer == true);
}
}
-- Sat Jul 24, 2010 8:30 pm --
I cleaned it up and fixed a bug where if you answered yes initially and then answered no, the program would keep running.
- Code: Select all
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean exclam = false;
boolean question = false;
String sentence;
boolean answer = false;
String reply;
do {
System.out.println("Please enter your question or concern: ");
sentence = keyboard.nextLine(); //stores input as string
switch (sentence.charAt(sentence.length() - 1))//checks for ! or ?
{
case '!':
exclam = true;
break;
case '?':
question = true;
break;
}
if ((sentence.length() % 2 == 0) && (question)) {//checks to see if even and question
System.out.println("Yes");
} else if ((sentence.length() % 2 != 0) && (question)) { //checks to see if odd and question
System.out.println("No");
} else if (exclam) { //checks to see if !
System.out.println("Wow");
} else if ((!question) && (!exclam))//checks to see if neither ! or ? are present
{
System.out.println("You always say " + sentence);
}
System.out.println("Would you like to ask another question?");
System.out.println("Enter yes or no: ");
reply = keyboard.next();
if (reply.equalsIgnoreCase("yes")) {
answer = true;
} else {
answer = false;
}
}
while (answer);
}
}