This is quite a beginner question but I'm wondering why my do...while loop is not closing.
The program is supposed to loop while the user input is not 'C', 'c', 'F', or 'f'.
It seems to close when just one boolean expression in the while section is valid but not if multiple are valid.
public class CelsToFaren
{
public static void main(String[] args)
{
// scanner setup
Scanner sc = new Scanner(System.in);
// Variable declarations
int celsius;
int answerC;
int farenheit;
int answerF;
char userLetter;
do
{
// initial menu options
System.out.println("Which temperature would you like to convert from? ");
System.out.println(" >(C)elsius ");
System.out.println(" >(F)arenheit ");
// user input of C, c, F, or f to select option
userLetter = sc.next().charAt(0);
// if user input C or c
if ((userLetter == 'C' || userLetter == 'c'))
{
System.out.print("Please enter the temperature: ");
celsius = sc.nextInt();
answerC = ((celsius*9/5)+32);
System.out.println("The answer is: " + answerC + " Farenheit ");
}
else
{
// if user input F or f
if ((userLetter == 'F' || userLetter == 'f'))
{
System.out.print("Please enter the temperature: ");
farenheit = sc.nextInt();
answerF = ((farenheit-32)*5/9);
System.out.println("The answer is: " + answerF + " Celsius ");
}
else
{
// if user input not F, f, C, or c
if ((userLetter != 'F' || userLetter != 'f' || userLetter != 'C' || userLetter != 'c'));
{
System.out.println("Please enter a valid option");
}
}
}
} while ((userLetter != 'c') || (userLetter != 'C') || (userLetter != 'f') || (userLetter != 'F'));
}
}
You need to change the exit logic.
In your case 1 | 0 | 0 = true so the loop continues.
You need to change it to:
while ((userLetter != 'c') && (userLetter != 'C') && (userLetter != 'f') && (userLetter != 'F'));
Your condition is wrong. Lets assume you want to break loop in if statement. It would look like
if(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F')
Now let's apply negation to get a condition under which you do not need to exit the loop
if(!(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F'))
this condition is simillar to
if(userLetter != 'c' && userLetter != 'C' && userLetter != 'f' && userLetter != 'F')
Related
Everytime i input my sentence it prints out the outcome each time it goes through the loop. i assume i have to put the printlines outside the loop?
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
System.out.println("There are " + count + " vowels in this string");
}
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
System.out.println("The vowels are: " + empty);
}
}
}
}
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
No need to check condition two times. As you are updating variables (count & empty) in loop, have to print only once after exiting from loop.
you just need to move the print statement outside and put a check condition if the count is still zero then it means there were no vowels and if count is not zero you can print it.
import java.util.Scanner;
public class homework4 {
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty = "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
if(count == 0){
System.out.println("There are no vowels in the input string");
}else {
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
}
You don't need to test for vowels twice? (and add to count twice), only once:-
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
count++;
empty += ch + " ";
}
And your print statement doesn't need to happen every time you find a vowel:-
for (int i = 0; i < userIn.length(); i++) {
// not in here
}
System.out.println("There are " + count + " vowels in this string\n" + "The vowels are: " + empty);
Additionally...
If statements are ugly here, where there are many conditions. A switch would be easier to read and more efficient:-
switch (ch){
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
count++;
empty += ch + " ";
break;
}
Or move the whole condition into a method
public boolean isVowel(char c){
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');
}
and use
if (isVowel(ch)){
//...
}
My goal is to get specific inputs from the user (A, B, C, and D only).
for example: If i enter the letter A, the if statement will execute (its not supposed to). and the same with the do while.
(Logic Error)
char[] response = new char[20];
Scanner k = new Scanner(System.in);
//Prompts User to fill array with their responses
for(int i=0; i<response.length; i++) {
//Input validation
do {
System.out.println("Answer "+(i+1)+":");
response[i] = k.nextLine().charAt(0);
if(response[i] != 'A' ||response[i] != 'B' || response[i] != 'C' ||response[i] != 'D')
System.out.print("Try Again. ");
}
while(response[i]!= 'A' ||response[i] != 'B' ||response[i] != 'C' ||response[i] != 'D');
}
This is how I would write it
Scanner in = new Scanner(System.in);
char[] response = new char[20];
//Prompts User to fill array with their responses
for(int i = 0; i < response.length; i++) {
for (;;) {
System.out.println("Answer " + (i + 1) + ":");
response[i] = in.nextLine().charAt(0);
//Input validation
if ("ABCD".indexOf(response[i]) >= 0)
break;
System.out.print("Please try again, it must be A, B, C or D");
}
}
What you were doing wrong is you needed to write
if (!(response[i] == 'A' || response[i] == 'B' || response[i] == 'C' || response[i] != 'D'))
OR
if (response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')
You condition is backwards. When you get it A you will get
if (false || true || true || true)
which will pass.
Change this to:
if(response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')
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'm super new to programming so I would love to keep this simple. The compiler accepts my code, but when I run the program and type in for example the letter A I just get a ton of errors. I tried earlier using String letter instead of int letter, but I just got compiler errors stating I couldn't convert Strings to characters or something. I'm really confused and could use a quick explanation and fix so I can get a number back. Here's my code:
import java.util.Scanner;
import java.lang.String;
public class PhoneAlgorithm {
public static void main(String[] args){
int digit = -1;
Scanner in;
in = new Scanner(System.in);
System.out.print("Enter an uppercase letter to find out the corresponding digit on a telephone: ");
int letter;
letter = Integer.parseInt(in.next());
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = 2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = 3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = 4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = 5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = 6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = 7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = 8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = 9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
if (digit != -1) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}
When you use parseInt(str), you will get an Exception if the parameter str cannot be converted to an integer.
You must use char, since you are comparing the input with single characters:
char letter;
letter = in.nextLine().charAt(0);
str.charAt(index) Returns the char value at the specified index.
I have modified your code, I guess this is what you are looking for..
import java.util.Scanner;
public class Try {
public static void main(String[] args) {
//declarations
char letter;
int digit=0;
// Asking the user to enterstring
System.out.println("Enter the string");
String enterString;
//creating a scanner object and reading the string
Scanner input = new Scanner(System.in);
enterString= input.next();
System.out.println("Entered string is "+enterString);
int temp=0;
for(int i=0;i<enterString.length();i++){
letter=(char)enterString.codePointAt(i);
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = digit*10+2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = digit*10+3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = digit*10+4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = digit*10+5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = digit*10+6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = digit*10+7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = digit*10+8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = digit*10+9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
/*if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}*/
}
if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}