I want my program to quit when I input "Q" or "q". However, the loop never finishes. Can you help me figure it out, please?
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
char str ;
do {
System.out.println("Choose one of the following option : ");
System.out.println("U or u - to convert SAR amount to USD");
System.out.println("E or e - to convert SAR amount to EURO");
System.out.println("Q or q - to quit");
str = input.next().charAt(0);
if (str == 'U' || str == 'u' ) {
}
else if (str == 'E' || str == 'e' ){
}
} while( str != 'Q' || str != 'q' );
}
str != 'Q' || str != 'q' is always true. Any given string is not equal to one or the other of these (or both). You want && instead of ||.
A nice structure to use would be the structure similar to the one recommended for getopt_long() in C but for Java obviously. Can read the man page here https://linux.die.net/man/3/getopt_long
while(true)
{
str = input.next().charAt(0);
if(str.toUpperString.equals('Q'))
{
break;
}
// In general if you want upper and lower case to do the same thing
//use toUpperString
switch (str) {
case 'U':
case 'u':
// Do something
break;
case 'E':
case 'e':
// Do something
break;
default:
System.out.println("Wrong input");
break;
}
}
Another good solution to this problem, if you don't want to use the switch statement, is the loop-and-a-half.
https://codehs.gitbooks.io/introcs/content/Basic-JavaScript-and-Graphics/loop-and-a-half.html
The structure goes like this:
while(true)
{
String token = Character.toUpperCase( input.next().charAt(0) );
if(token.equals('A'))
{
// Do something
}
else if(token.equals('B'))
{
// Do something
}
else if(token.equals('Q'))
{
break;
}
else
{
System.out.println("Invalid Option");
}
}
If you want to stop the program when you write Q or q. you can convert the input to any of the lower or uppercase.
str.toUpperCase();
if (str == 'U'){
}
else if (str == 'E'){
}
} while( str != 'Q');
}
OR
change the condition for checking Q or q.
while( str != 'Q' && str != 'q' );
for the above code snippet, the while loop will execute if str is not Q or q.
public static void main(String [] args) {
Scanner input= new Scanner(System.in);
char str ;
do{
System.out.println("Choose one of the following option : ");
System.out.println("U or u - to convert SAR amount to USD");
System.out.println("E or e - to convert SAR amount to EURO");
System.out.println("Q or q - to quit");
str = input.next().charAt(0);
if (str == 'U' || str == 'u'){}
else if (str == 'E' || str == 'e'){}
} while(str != 'Q' && str != 'q'); // change the condition from || to &&
// Also close the input stream to avoided memery leakage
input.close();
}
Related
I need to create a program that asks the user for a string value and returns a string value of "rock" "paper" or "scissors" if the input was "r" "p" or "s" If the user typed in something different.
package loopsGamesProject;
import java.util.Scanner;
public class LoopsGamesProject_RockPaperScissors {
public static void main(String[] args) {
String in="-";
Scanner input= new Scanner(System.in);
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
while(in!="r"||in!="p"||in!="s") {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
}
}
input.close();
System.out.print(in);
}
}
}
The issue is, it will ask for a variable, but the terminate itself. I've tried adding an "out" variable. When I tried to do this using a do while loop, it kept asking for an input but never returned anything. I can't find the issue.
When you compare Strings in java, you need to use the .equals() method instead of the == function. This rule applies for all objects in java, String inclusive.
EG:
if (in.equals("r"))
//Rock!
You also need to replace the != and add a break statement to exit the loop. Something like this will do:
while (!(in.equals("r") || in.equals("p") || in.equals("s"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else
in = "Scissors";
break;
}
}
EDIT: The above prompts twice. This will fix it:
public static void main(String[] args) {
String in = "";
Scanner input = new Scanner(System.in);
while (!(in.equals("Rock") || in.equals("Paper") || in.equals("Scissors"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r")) {
in = "Rock";
}
if (in.equals("p")) {
in = "Paper";
}
if (in.equals("s")) {
in = "Scissors";
}
break;
}
}
input.close();
System.out.print(in);
}
As has been mentioned, you need to compare String equality using the String.equals(Object anObject) - alternatively you may use others methods (compareTo), but the == operator will not suffice (See here why).
On top of this, when you match the String you overwrite the String with the full word - in = 'r'; -> in = 'Rock';. But the condition you use to loop will only terminate when in is r, p or s specifically.
Further, you have some duplicated code there that could be reduced significantly. This is not a bug, but this can become very difficult to manage very quickly.
All things considered:
while (true) {
// Get the next input
in = input.next();
// Maps the word to the character
// If a word was not mapped, try again.
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else if (in.equals("s"))
in = "Scissors";
else
continue;
// Terminate the loop as you can infer a match was found.
break;
}
I have a static function which gets and returns a char input.
It will then check the input using a while loop.
After my main method gets the input, the result will display accordingly to the user input.
Below is my method:
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char choice = getInput(sc);
String result;
switch (choice)
{
case ('a'): result = "u choose A";
break;
}
}
private static char getInput(Scanner keyboard)
{
Scanner sc = new Scanner(System.in);
System.out.println("a, b, c, d, e, q: ");
char choice = sc.nextLine().trim().toLowerCase().charAt(0);
while (choice != 'a' || choice != 'b' || choice != 'c' || choice != 'd' || choice != 'e' || choice != 'q')
{
System.out.println("You have entered an invalid entry.");
System.out.println("a, b, c, d, e, q: ");
choice = sc.nextLine().trim().toLowerCase().charAt(0);
}
return choice;
}
}
However, I am getting the result of invalid input even though I entered the character 'a'.
May I know which part have I gone wrong?
This condition:
while (choice != 'a' || choice != 'b' || choice != 'c' || choice != 'd' || choice != 'e' || choice != 'q')
will always return true if your choice is not a or is not b or is not c, etc. Change those || operators to && operators and you should be good to go.
What I want is no matter what the user inputs, if the first letter of their input is either a 'y' or 'n' regardless of case, it will print "game start".
I've tried equalsIgnoreCase() with the "letter" variable but it gives the error: char cannot be dereferenced. Any recommendations will be really appreciated on this! Thanks!
Scanner input = new Scanner(System.in);
System.out.println("Do you want to continue?");
String wesker = input.nextLine();
char letter = wesker.charAt(0);
if(letter == 'y' || letter == 'p'){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
Try use Character#toLowercase():
if (Character.toLowerCase(letter) == 'y' || Character.toLowerCase(letter) == 'n') {
or
if (Character.toUpperCase(letter) == 'Y' || Character.toUpperCase(letter) == 'N') {
or simply
if( letter == 'y' || letter == 'Y' || letter == 'n' || letter == 'N' )
Just check against both cases:
if( letter == 'y' || letter == 'Y' || letter == 'p' || letter == 'P' )
equalsIgnoreCase can be used only by Strings. For your case, if you want to use that method, you can do this:
Scanner input = new Scanner(System.in);
String wesker = input.nextLine();
String letter = wesker.substring(0,1);
if(letter.equalsIgnoreCase("y") || letter.equalsIgnoreCase("n")){
System.out.println("Game start");
} else {
System.out.println("Game over");
}
You could pre-build a set of acceptable characters.
Set<Character> yes = new HashSet<>(Arrays.asList('y','Y','p','P'));
public void test() {
char letter = 'c';
if ( yes.contains(letter)) {
}
}
I was wondering as to how I could get the end of the program to repeat if the user does respond with a 1. Do I need to reorganize it so that it is part of the if statement?
Scanner input = new Scanner(System.in);
System.out.println("Count Vowels \n============");
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int answer;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() + Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
if (answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
} else {
System.out.println("Have a nice day");
}
You can do this with a do/while loop. The skeleton for this kind of loop looks like this:
Scanner input = new Scanner(System.in);
do {
// do your stuff here
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
} while(input.nextInt() == 1);
System.out.println("Have a nice day");
It asks the user and evaluates the entered number in the while(input.nextInt() == 1) statement. If this comparison returns true (i.e. user entered 1), then the loops starts again. If not (i.e. user entered something else than 1), the loop stops and you'll get the "Good Bye" message instead.
you can split this up into more than one method and using one primary method call other methods inside a while loop. for example:
boolean continueCounting = false;
void countingVowels() {
//some start game method to make continueCounting = true
//something like "press 1 to start"
//if (input == 1) { continueCounting = true; }
while(continueCounting) {
String userInput = getUserInput();
countVowels(userInput); //count vowels in word from user input and prints them out to console
getPlayAgainDecision(); //ask user to put 1 or 2
if (answer == 1) {
continue
} else if (answer == 2) {
continueCounting = false;
} else {
System.out.println("incorrect input, please choose 1 or 2");
}
}
}
There are many ways to do this. A search on Google would have lead you to the correct answer in less time than it took you to ask the question. However, since you took the time to ask the question here is the answer:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int answer = 0;
System.out.println("Count Vowels \n============");
// the do-while loop ensures that the code is executed at least once
do {
// on the first run answer equals zero, but on other runs it will equal one
if(answer == 1) {
System.out.println("You have chosen to count the vowels in another phrase");
}
System.out.println("Type a sentence and this program will tell you\n\nhow many vowels there are (excluding 'y'):");
String string1;
string1 = input.nextLine();
string1 = string1.toLowerCase();
int vowels = 0;
int i = 0;
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i'
|| letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase()
+ Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
}
System.out.println("Would you like to check another phrase in the Vowel Counter? If so type 1 if not type 2 and press enter");
answer = input.nextInt();
} while (answer == 1);
System.out.println("Have a nice day");
}
}
In your code you assert that a letter is a vowel if it is in the set a, e, i, o and u which is true. However, the letter y can be a vowel in certain situations.
In general, the Y is a consonant when the syllable already has a vowel. Also, the Y is considered a consonant when it is used in place of the soft J sound, such as in the name Yolanda or Yoda.
In the names Bryan and Wyatt, the Y is a vowel, because it provides the only vowel sound for the first syllable of both names. For both of these names, the letter A is part of the second syllable, and therefore does not influence the nature of the Y.
You could expand on your code even more by checking if the letter y is a vowel or not.
This is a more elegant way to do the counting (I updated the code to satisfy Johnny's comment that my previous answer didn't answer OP's question. The code now loops without unnecessary code):
public static void main(String... args)
{
int answer = 0;
Scanner input = null;
do
{
input = new Scanner(System.in);
System.out.print("Type a sentence and this program will tell you\nhow many vowels there are (excluding 'y'):");
String sentence = input.nextLine();
int vowels = 0;
String temp = sentence.toUpperCase();
for (int i = 0; i < sentence.length(); i++)
{
switch((char)temp.charAt(i))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
vowels++;
}
}
System.out.println("The sentence: \"" + sentence + "\" has " + vowels + " vowels");
System.out.print("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press any other key... ");
String tempNum = input.next();
try
{
answer = Integer.parseInt(tempNum);
} catch (NumberFormatException e)
{
answer = 0;
}
System.out.println();
} while (answer == 1);
input.close();
System.out.println("Have a nice day");
}
Notice that at the end, I catch a NumberFormatException for more robustness validation of the user's input.
Just put the main for loop inside a do-while loop, like so:
do
{
for (String Vowels : string1.split(" ")) {
for (i = 0; i < Vowels.length(); i++) {
int letter = Vowels.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowels++;
}
}
System.out.println(Vowels.substring(0, 1).toUpperCase() +
Vowels.substring(1) + " has " + vowels + " vowels");
vowels = 1;
System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1 if not press 2");
answer = input.nextInt();
}
} while (answer == 1);
System.out.println("Have a nice day");
Additionally, there are better ways to do the counting, for example:
for (char c : string1.toCharArray())
{
c = Character.toLowerCase(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
I am trying to create a menu in the console and have the user select an option, for some reason when I run the application it goes straight to the else, bypassing options a-d.
import java.util.Scanner;
public class UserChoice {
public static void main(String[] args)
{
boolean status = true;
while (status == true)
{
System.out.println("");
System.out.println("MENU");
System.out.println("");
System.out.println("A : String Functions");
System.out.println("B : Simple Arithmetic Functions");
System.out.println("C : Temperature Conversion");
System.out.println("D : Sequences");
System.out.println("E : Exit Application");
System.out.println("");
System.out.println("Please make a selection.");
Scanner keyboard = new Scanner(System.in);
String choice =null;
choice = keyboard.nextLine();
if (choice == "a" || choice == "A")
{
StringFunctions();
}
else if (choice == "b" || choice == "B")
{
ArithmeticFunctions();
}
else if (choice == "c" || choice == "C")
{
TemperatureConversion();
}
else if (choice == "d" || choice == "D")
{
Sequences();
}
else if (choice == "e" || choice == "E")
{
System.exit(0);
}
else
{
System.out.println("You have entered an invalid selection, please choose again.");
}
}
}
All String/Object comparisons should use equals() method instead of == (except String literals)
if (choice.equals("a") || choice .equals( "A")){....}
Apply same change to other else/if blocks also.
== compares reference equality. equals() method checks for content equality.
You may want to make sure that at least one character is entered:
String choiceString ="";
while(choiceString.length() <1){
choiceString = keyboard.nextLine();
}
Once done, you may want to get the first character from the string as:
char choice = choiceString.charAt(0);
now since your choice is char, you may write your conditions using single quote as below:
if (choice == 'a' || choice == 'A'){
.......
......
Also if you want, you want to change the case of String entered to upper or lower case, get the char and then use simpler conditions as below:
char choice = choiceString.toUpperCase().charAt(0);
if (choice == 'A'){
.....
}else if(...