Simple switch in "for" loop and toLowerCase() method - java

I am very much a beginner in Java. I am making a simple switch, in which the user is entering a number in words. For training I added a "for" loop.
package JavaExc;
import java.util.Scanner;
public class JavaStart {
public static void main(String[] args) {
Scanner sck = new Scanner(System.in);
System.out.println("Type loop counter ");
int counter = sck.nextInt();
System.out.println("Counter is: " + counter );
for (int i = 0; i <= counter; i++) {
System.out.println("Type number in words");
String ch = sck.nextLine();
switch (ch.toLowerCase()) {
case "one":
System.out.println("CHOICE 1");
break;
case "Two":
System.out.println("CHOICE 2");
break;
case "THREE":
System.out.println("CHOICE 3");
break;
case "FoUr":
System.out.println("CHOICE 4");
break;
case "fiVE":
System.out.println("CHOICE 5");
break;
default:
System.out.println("Wrong Data");
break;
}
System.out.println("Loops left:\n " + counter--);
}
System.out.println("End of Switch");
}
}
Here is the result:
Type loop counter
5
Counter is: 5
Type number in words
Wrong Data // ??
Loops left:
5
Type number in words
one
CHOICE 1
Loops left:
4
Type number in words
three // Should be ok, so what is wrong here?
Wrong Data
Loops left:
3
End of Switch //To early break loop I think
Process finished with exit code 0
My questions are: Why first loop make default code? Should I make 2 Scanners? One for take value for counter and second for switch?
Why counter and numbers in words do not working properly?
I know I can do it with tables etc. but generally, the purpose of this program is to test the "toLowerCase()" method.

You're checking your string in lower case ("three") against upper case ("THREE"). Make sure they're both identical and it shouldn't fail.

Switch statement
In your switch clause, you are testing a String that has been turned into a lowercase form of itself. Therefore, the only possible case clause that will be matched is "one", as the others all contain uppercase characters.
Change all of the case clauses to lowercase and it will work, as long as you input the data correctly.
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
Not accepting input
Regarding your problem with the program not accepting input, you have to call sck.nextLine() after calling sck.nextInt(), see here for details on why this is.
Only one scanner is necessary.

The convention of a switch statement is similar to an if-else if-else chain. The value placed between the switch statement's parenthesizes is evaluated against every case present in the switch statement.
A switch statement of:
String condition = "foo";
switch(condition){
case "example":{
}
case "foo":{
}
case "bar":{
}
default:{
}
}
is similar to the expression:
if(condition.equals("example")){
}else if(condition.equals("foo")){
}else if(condition.equals("bar")){
}else{
}
Note that by making your input into the switch statement lowercase, it will never match any case that is uppercase.
e.g:
if("tHREE".toLowerCase().equals("tHREE")){
will never evaluate true, since "tHREE" is first being dropped to all lowercase "three" before performing a case-sensitive comparison to "tHREE".

Why first loop make default code?
As explained in Skipping nextLine() after use next(), nextInt() or other nextFoo() methods, nextInt doesn't consume the newline character. Add a call to sck.nextLine(); after setting counter.
Should I make 2 Scanners? One for take value for counter and second for switch?
No, only one Scanner is necessary.
Why counter and numbers in words do not working properly?
First, your for loop condition is i <= counter, which means that it's set up to run counter + 1 times. Change it to i < counter.
Second, your switch cases except for "one" contain capital letters, so they will never match ch.toLowerCase(). Change your case labels to strings with all lowercase letters.
Third, you decrement counter at the end of the for loop, cutting down on the number of iterations run. Instead, use the expression (counter - i - 1) to output the number of loops left.

retype the cases to:
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;

Ok i added changes and it works fine. Now I will try to make possibilty to input words whatever they are upper or lower cases. Thanks for help! StackOverflow rocks so much!
package JavaExc;
import java.util.Scanner;
public class JavaStart {
public static void main(String[] args) {
Scanner sck = new Scanner(System.in);
System.out.println("Type loop counter ");
int counter = sck.nextInt();
sck.nextLine();
System.out.println("Counter is: " + counter );
int i;
for ( i = 0; i < counter; i++) {
System.out.println("Type number in words");
String ch = sck.nextLine();
switch (ch.toLowerCase()) {
case "one":
System.out.println("CHOICE 1");
break;
case "two":
System.out.println("CHOICE 2");
break;
case "three":
System.out.println("CHOICE 3");
break;
case "four":
System.out.println("CHOICE 4");
break;
case "five":
System.out.println("CHOICE 5");
break;
default:
System.out.println("Wrong Data");
break;
}
System.out.println("Loops left:\n " + (counter - i - 1) );
}
System.out.println("End of Switch");
}}

Related

How can I make the program stop after entering a value from a user?

I am trying to write a program that receives the number of sides from the
user and determines the type of figure using switch structure and a while sentinel-controlled loop, but every time I get an infinite loop. How can that be fixed?
import java.util.Scanner;
public class P1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of sides:");
int s = input.nextInt();
while ( s!=-1)
{
switch (s)
{
case 1: System.out.println("Line");
break;
case 2:System.out.println("Angle");
break;
case 3:System.out.println("Triangle");
break;
case 4:System.out.println("Quadrilateral");
break;
case 5:System.out.println("Pentagon ");
break;
case 6:System.out.println("Hexagon");
break;
case 7:System.out.println("Heptagon");
break;
case 8:System.out.println("Octagon");
break;
case 9:System.out.println("Nonagon");
break;
case 10:System.out.println("Decagon");
break;
default: System.out.println("Enter a valid value:");
}
}
}
}
The while loop is written to continue as long as s!=-1; so you need to change s so that this expression is no longer true.

Conditional wont be read in do while statement

For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.
import java.io.*;
import java.util.*;
public class Prog213c
{
public static void main(String[] args) {
Scanner kbReader=new Scanner(System.in);
do{
System.out.println( "Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits)
{
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default: System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
String answer = kbReader.next();
} while (answer == 'y'); // error received here
You have a few problems here:
String answer = kbReader.next();
} while (answer == 'y'); // error received here
Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.
This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".
Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.
You could do something like:
case 30:
case 31:
case 32: // ...
but that seems like a thoroughly painful way to do that. See also this question for more details.
This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:
switch ((int) num/10) {
case 1:
System.out.println("10-19");
break;
case 2:
System.out.println("20-29");
break;
case 3:
System.out.println("30-39");
break;
case 4:
System.out.println("40-49");
break;
default:
break;
}
(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).
Also:
int studentNumber = kbReader.nextInt();
You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?
Single quotes are character literals in Java. So you can't compare a
String with a char directly.
Your answer variable has to be declared before the do-while loop.
you have to use the equals method to compare strings.
answer.equals("y")
Problem 1:
since answer is a string object, this is not working (answer == 'y');
you can do "y".equals(answer) is you get the nextLine from the scanner
or if you need to work with chars
char x = kbReader.next().charAt(0);
while (x == 'y');
Problem 2:
answer must be declared before the do-while loop...
your final code can look like
Scanner kbReader = new Scanner(System.in);
char answer = 'y';
do {
System.out.println("Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits) {
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default:
System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
answer = kbReader.next().charAt(0);
} while (answer == 'y');
Change your while condition to:
while ("y".equals(kbReader.next()));

Using switch statements for a playing cards program (Java)

I have my program figured out so far, it's just that I'm not understanding these instructions I was given (or at least understanding how to do them).
When I type 10, it prints out "10 of", but when I try to type 10S for 10 of Spades, it only prints out "Spades."
Hopefully, someone here can give me either a solution or point me in the right direction on how to solve my problem:
Use a SWITCH statement to assign the result variable an initial value - the value of the card
Use a second SWITCH statement to concatenate to the result variable the card's suit"
here is the code:
import java.util.*;
public class CardConverter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//will hold string that user will input
String card, face, suit, result;
//getting input from user and telling them correct format
System.out.println("Please enter either the number or face value intial of a card followed by the initial of it's suit (ie. QH for Queen of Hearts)");
card = keyboard.nextLine();
//gets first value
face = card.substring(0);
//sets substring for 10 only
//substring for after all single digit/letter card faces
suit = card.substring(1);
//to print face and word of
switch (face)
{
case "10":
System.out.println("10 of ");
break;
case "2":
System.out.println("2 of ");
break;
case "3":
System.out.println("3 of ");
break;
case "4":
System.out.println("4 of ");
break;
case "5":
System.out.println("5 of ");
break;
case "6":
System.out.println("6 of ");
break;
case "7":
System.out.println("7 of ");
break;
case "8":
System.out.println("8 of ");
break;
case "9":
System.out.println("9 of ");
break;
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
}
//to print out card suit
switch (suit)
{
case "H":
System.out.println("Hearts");
break;
case "C":
System.out.println("Clubs");
break;
case "S":
System.out.println("Spades");
break;
case "D":
System.out.println("Diamonds");
break;
}
}
}
Your problem starts at card.substring(0);, which equals card because the substring from the start of the String. Maybe you wanted card.charAt(0);? But that is also wrong because "10S" will have three characters, two for the face value.
You'll need to handle a three-character input specially or be smarter about the substring-ing.
You know the suit will always be the last character, so use the length of the string to charAt for that.
int suitIndex = s.length() - 1;
String suit = ""+s.charAt(suitIndex);
String face = s.substring(0,suitIndex);
You can also simplify the cases
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
default:
System.out.println(face + " of "); // handle all the numbers
break;

switch loops? while loops? currency converter program java

I am new to switch loops and am having multiple problems with this currency converter program I am trying to create.
First, I would like to loop the case 1 where the user keeps entering values until they type -1 so it stops and moves on. At the moment, it does not do this. Once I've entered the GPR values on switch 1 and then loop back to the menu keeping the original GPR stored values.
Code is here:
import java.util.Scanner;
public class Conversion {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int Choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
Choice = input.nextInt();
switch (Choice) {
case 1:
while (!exchange.equals("-1"));{
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange (Type '-1' to stop) ");
}
case 2:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in euros are" + poundDollars);
case 3:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in euros are" + poundYen);
case 4:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in euros are" + poundRupees);
case 5:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in euros are" + poundEuro);
case 6:
break;
}
input.close();
exchange.close();
}
}
switch is not a loop. It's a branching statement like if. It has break, but that is only present because you can "fall through" to the next case statements. Currently you are falling through on most of them, because you've forgot putting in the break statements between the cases.
A switch statement isn't a loop. Consider it a replacement for a series of else-if statements. Your code actually reads more like this:
if(Choice == 1)
{
}
else if(Choice == 2)
{
}
else if(Choice == 3)
{
}
else if(Choice == 4)
{
}
else if(Choice == 5)
{
}
else if(Choice == 5)
{
}
However, your switch cases should be terminated with break statements. If one is not, unlike the else-ifs above, execution will fall-through to the next case and execute the code in that one too, until it finally reaches a break statement or goes through all the cases.
What you want is for your while-loop to wrap AROUND your switch statement, but you should fix your while-loop first, since you terminated it with a semicolon, it is infinite. While-loops don't need a semicolon at the end, unless you do not have a body for it but you do have some side-effect happening in the conditional check that will eventually cause it to end.
while( blah )
{
switch( blah )
{
case 1:
// Do stuff for this case
break;
case 2:
// Do stuff for this case
break;
default:
// Do stuff when no case is matched
break;
}
}
I think you're a bit confused. As noted by immibis in his comment, switch statements are not loops, so you need to enclose the switch statement inside a loop.
Then, you're missing the break statements at the end of each case. Quoting the Java tutorials:
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Your program should be something like this:
public static void main(String[] args) {
// Variable definitions
while(true) { // This is a little trick to force the application to repeat
// a task until you explicitly break the loop
// Code to print your menu
choice = input.nextInt();
if(choice == -1 || choice == 6)
break; // Break the while loop if choice is -1 or 6
switch(choice){
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
If you don't put those break statements at the end of each case block, your program will fall through every option.
Please read:
The Java tutorials: The switch statement
The Java tutorials: The while statement
Another option would be something like this:
public static void main(String[] args) {
// Variable definitions
/*
Now let's use a labeled loop
*/
menu: while(true) {
// Code to print your menu
choice = input.nextInt();
switch(choice){
case -1: // Nothing goes here, so the execution will fall through
// to the next case
case 6:
break menu; // This will break the menu loop.
// Since the previous case simply falls through to
// this one, this will happen if choice is
// either -1 or 6
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
More reading:
The Java tutorials: Branching statements

Java Switch Statement: creating a calculator error

I was wondering if anyone can see what is wrong with my code. It works except that the program is not acknowledging my switch statement - I searched lots of questions but as I am a novice I am clearly missing something.
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}
You should be using switch(operatorOpt). Right now you are switching on the first number.
You also need to change:
int operatorOpt= 0;
operatorOpt = input.nextInt();
That is, if you want to keep your switch statement the same. Please also see #Daniel Imms answer for an additional bug fix.
Try adding a break at the end of case 4
case 4:
result=no1/no2;
break;
EDIT J L's answer is the main issue, but this is another problem that will break division.
Your switch should be on the operatorOpt and not on no1.
Also, you're missing a break in the case 4. So, if you want to do a division, you'll get 0 as result.
The input from the user for operatorOpt should be done with input.nextLine(). Or, if you want to keep the same switch statement, with input.nextInt().
It should be like this:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}
Your switch statement should be on "operatorOpt" and not on "no1" as you suppose to check the operator and based on that you want to do the calculation. However, you must use JDK1.7 to use String in Switch statement since previous versions of JDK do not support String Switch.
Also, you should use "break" in case 4.
Your switch should be on the operatorOpt and not on no1.
You can use like this
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}

Categories