Im writing a program in java that is suppose to receive a phone number as a string, (ex. 1800helpmee) from the user and print out its corresponding numbers. 1800 435 7633 should be the answer. this is the code i have so far. I've loaded the number into the array. I am having an issue with the next part. my array is called inputNumber. I tried something like this but it doesn't seem to be working
for (int j = 0; j<9; j ++) {
if ( inputNumber[j] =='A' || inputNumber[j] == 'B' || inputNumber[j] =='C'){
System.out.println("2");
} etc.
switch inputNumber[j] =='A' to inputNumber[j].equalsIgnoreCase("a") apply this for a, b and c then retry
You could use a for each loop to iterate the strings array
public static void main(String[] args) {
String [] inputNumber = {"1","8","0","0","h","e","l","p"};
for (String number : inputNumber) {
switch (number.toUpperCase()) {
case "A":
case "B":
case "C":
System.out.println("2");
break;
case "D":
case "E":
case "F":
System.out.println("3");
break;
// other letters
default:
System.out.println(number);
}
}
}
Evaluate each letter with a switch (as of Java 7) and print the aproppriate number. Notice the fall through, a break statement after several case. The toUpper() method is called to compare only with the uppercase version of each letter.
Related
Why is it that the following code:
class swi
{
public static void main(String[] args)
{
int a=98;
switch(a)
{
default:{ System.out.println("default");continue;}
case 'b':{ System.out.println(a); continue;}
case 'a':{ System.out.println(a);}
}
System.out.println("Switch Completed");
}
}
Gives the error:
continue outside of loop
Falling through is the standard behavior for a switch statement and so, consequently, using continue in a switch statement does not make sense. The continue statement is only used in for/while/do..while loops.
Based on my understanding of your intentions, you probably want to write:
System.out.println("default");
if ( (a == 'a') || (a == 'b') ){
System.out.println(a);
}
I would also suggest that you place the default condition at the very end.
EDIT:
It is not entirely true that continue statements cannot be used inside switch statements. A (ideally labeled) continue statement is entirely valid. For example:
public class Main {
public static void main(String[] args) {
loop:
for (int i=0; i<10; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 9:
continue loop;
}
System.out.println(i);
}
}
}
This will produce the following output:
0
2
4
6
8
The continue-Statement may be used in loops and not in switch. What you probably want is a break.
Because you have a continue outside of a loop. continue is for jumping to the next iteration of a loop, skipping the remainder of the current iteration. But you don't have any loop in that code. What you want for breaking out of a switch case block is the keyword break (see below).
There's also no need to put every case block within braces (unless you want locally-scoped variables within them).
So something a bit like this would be more standard:
class swi22
{
public static void main(String[] args)
{
int a=98;
switch(a)
{
default:
System.out.println("default");
break;
case 'b':
System.out.println(a);
break;
case 'a':
System.out.println(a);
break;
}
System.out.println("Switch Completed");
}
}
There's also a school of thought that says the default condition should always be at the end. This is not a requirement, just a fairly widely-used convention.
Shouldn't you use break instead of continue?
continue simply moves directly to the next iteration of the loop.
break is used to break out of loops and switches.
Use break; instead of continue;
Continue:
for(x = 0; x < 10; x++)
{
if(x == 3)
continue;
else
DoIterativeWork();
}
Switch:
switch(a)
{
default:{ System.out.println("default"); break;}
case 'b':{ System.out.println(a); break;}
case 'a':{ System.out.println(a);}
}
You are using continue where you should be using break
continue inside switch??!!! only break can be kept inside switch.!
ur code should be,
class swi22
{
public static void main(String[] args)
{
int a=98;
switch(a)
{
default:{ System.out.println("default");break;}
case 'b':{ System.out.println(a); break;}
case 'a':{ System.out.println(a);}
}
System.out.println("Switch Completed");
}
}
I am creating a decoder program that will essentially turn numbers into specific letters using a while loop but I'm having difficulties figuring out what's wrong with my code and also if there is a simpler way to put it using switch for example. Here is what I have so far:
import java.util.Scanner;
public class Decoder{
public static String decode(String str){
int i = 0;
while(i<str.length()){
if(str.charAt(i)=='1')
return("D");
else if(str.charAt(i)=='2')
return("W");
else if(str.charAt(i)=='3')
return("E");
else if(str.charAt(i)=='4')
return("L");
else if(str.charAt(i)=='5')
return("H");
else if(str.charAt(i)=='6')
return("O");
else if(str.charAt(i)=='7')
return("R");
return("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
public static void main(String[] args){
System.out.println("Enter a number ");
}
}
Sure. Use a constant char array as a lookup table.
At index 0, store 'D'. At index 1, store 'W', etc.
Whenever you encounter a number in the source, subtract '1' to it to get the index in the array for this number, and get the matching letter from the array.
The code is left as an exercise.
Other than the array mentioned by JB Nizet, you could try:
switch statement
a Map<Integer, String> containing the digit/letter pairs
You can use StringBuilder and switch/case like that:
public class Decoder {
public static String decode(String str) {
int i = 0;
StringBuilder decodedString = new StringBuilder();
while (i < str.length()) {
switch (str.charAt(i)) {
case '1':
decodedString.append("D");
break;
case '2':
decodedString.append("W");
break;
case '3':
decodedString.append("E");
break;
case '4':
decodedString.append("L");
break;
case '5':
decodedString.append("H");
break;
case '6':
decodedString.append("O");
break;
case '7':
decodedString.append("R");
break;
default:
return ("Sorry, you must input numbers from 1-7 inclusive");
}
i++;
}
return decodedString.toString();
}
public static void main(String[] args) {
while (true) {
System.out.println("Enter a number: ");
Scanner input = new Scanner(System.in);
System.out.println(decode(input.next()));
System.out.println();
}
}
-So in case 2, i'm trying to have the user to input elements (N,Y,P,D,G) only with specific Array location. I used switch inside a switch, but how do i re-loop if he enters wrong elements?
-in case 3, i'm trying to print the whole 2D array, but the original array is filled with the element G.
-in case 4, i'm trying to change the map view to the symbols.
Just found this as a practice, trying to learn, to some point, beginner complex programming, so any help is appreciated and any criticism is highly appreciated because i want to have a good basic knowledge of java :)
import java.util.Scanner;
public class Studyone {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int row;
int col;
int row1; //for case 2, so it would allow the user to input the element in the request array
int col1;
System.out.println("Enter the row: ");// knowing the row and the col of the 2D array to base the rest on.
row = input.nextInt();
System.out.println("Enter the col: ");
col = input.nextInt();
String sentence;
String sentence2;
String sentence3;
String tempelement;
String N;
String Y;
String G;
String P;
String D;
int choice;
System.out.println("The menu\n1)Enter the Elements in order\n2)Enter the the Col and row number spec.\n3)Show the Orig. map as is\n4)Show symbolic map.");
choice = input.nextInt();
System.out.println(choice);
String [][] map = new String[row][col];
switch (choice)
{
case 1:
sentence3=input.nextLine(); // for some reason it auto enters the first map [0][0] as null, this line allows the user to input the map[0][0]
map[0][0]=sentence3;
for (int i = 0; i < map.length; i++)
{
for (int j = 0;j < map[i].length; j++)
{
System.out.println("Enter the element");
sentence2 = input.nextLine();
map[i][j]=sentence2;
}
System.out.println(map[1][1]);
System.out.println(choice);
}
break;
case 2:
System.out.println("Enter the row");
row1 = input.nextInt();
System.out.println("Enter the col");
col1 = input.nextInt();
System.out.println("Enter the element you want to enter");
tempelement = input.nextLine();
switch (tempelement)
{
case "Y":
map[row1][col1] = tempelement;
case "N":
map[row1][col1] = tempelement;
case "P":
map[row1][col1] = tempelement;
case "D":
map[row1][col1] = tempelement;
case "G":
map[row1][col1] = tempelement;
}
System.out.println(tempelement); // test,does not let me enter any temp elements, lets it empty in the input without letting the use enter anything. Figure out error
System.out.println(choice); // test, prints the right choice, Correct.
break;
case 3:
for (int i=0;i > map.length;i++)
{
for (int j=0; j > map[i].length; j++)
{
map[i][j] = N;
// print statment, need to find how to do.
}
}**strong text**
break;
case 4:
// having symbols instead of the letters, N=* , P= ~ , Y=. , G= #, D=#
//
}
}
}
Case 2:
I don't know why you're using a switch statement within to check if the cases are either N,Y,P,D or G. In order to check for correct inputs, you could use a while loop and break when the correct input is placed.
System.out.println("Enter the row");
row1 = input.nextInt();
System.out.println("Enter the col");
col1 = input.nextInt();
while(true){
System.out.println("Enter the element you want to enter");
tempelement = input.nextLine();
if(tempelement.equals("N") || tempelement.equals("Y") || tempelement.equals("P") || tempelement.equals("D") || tempelement.equals("G")){
map[row1][col1] = tempelement;
break;
}
}
Case 3:
To print a 2D array, you need a nested for loop. It requires 2 for loops.
for(int i=0; i<map.length; i++){
for(int j=0; j<map[i].length; j++){
System.out.print(map[i][j]);
}
System.out.print("\n"); // this is for spacing after a row of element prints
}
Case 4:
This is the same as Case 3, just within the inner for-loop, you would have an if-else statement block or switch block to print out a symbol instead of a map. For example,
...
for(int j=0; j<map[i].length; j++){
switch(map[i][j]){
case "N": System.out.print("Symbol"); break;
case "P": ... code
... code
}
}
sentence3=input.nextLine(); // for some reason it auto enters the first map [0][0] as null, this line allows the user to input the map[0][0]
Use input.next() instead of nextLine().
Scanner.nextLine() as described in official document is:
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
After nextInt() is called it isn't properly terminating the allocated line of memory. So when nextLine() is called first time it is actually terminating the previous line that actually had value in it -- entered via nextInt() rather than taking in a new String value. That's why sentence3 is getting null value.
So in case 2, i'm trying to have the user to input elements
(N,Y,P,D,G) only with specific Array location. I used switch inside a
switch, but how do i re-loop if he enters wrong elements?
You can try in this way:
boolean bVaildInput = true;
do{
System.out.println("Enter the element you want to enter");
tempelement = input.next();
switch (tempelement)
{
case "Y":
map[row1][col1] = tempelement;
break;
case "N":
map[row1][col1] = tempelement;
break;
case "P":
map[row1][col1] = tempelement;
break;
case "D":
map[row1][col1] = tempelement;
break;
case "G":
map[row1][col1] = tempelement;
break;
default :
System.out.println("Invalid Input");
bValidInput = false;
}
}while(!bVaildInput);
in case 3, i'm trying to print the whole 2D array, but the original
array is filled with the element G.
for (int i=0;i < map.length;i++)
{
for (int j=0; j < map[i].length; j++)
{
System.out.print(map[i][j]+"\t");
}
System.out.print("\n");
}
in case 4, i'm trying to change the map view to the symbols.
Show some effort.
Since you are using this as practice, I'm not going to answer your problems but provide some insight into what it is that is going on and some links to look into:
Case 2:
You don't really need a second switch here. Look at the code for each case in the switch, it is exactly the same. What you want to use is a while loop and test that the input is valid. That way if the user enters invalid input it will ask them to try again. See Example 3 in this post
Case 3: There are plenty of examples out there of how to print 2D arrays - it depends on how you want it to look. I Suggest looking at this example
Case 4: This really is just an extension of Case 3 except rather then printing out the stored Input letter, print out the symbol. This is where a second switch statement maybe useful.
I need the syntax for adding in the variable parameter to a switch case that already has lots of parameters. The context is provided below.
I'm using a switch case to change a string answer to an integer return. Instead of having the user answer
1. This.
2. Something else.
I want the answer to look like
(y/n)
I've done it before with a code like this:
static public int getYN() {
String answer = "";
switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
And then using the statement:
int getAnswer = getYN();
System.out.println();
if (getAnswer == 1) {
System.out.println("Stuff.");
test = 1;
}
else {
System.out.println("Other stuff.");
System.out.println();
}
But, I don't know where to put the String answer variable into the switch case. Usually, if you aren't using many other parameters, it would just be
switch(answer) {
}
Check it inline, forget having a dedicated method to doing this check.
char getAnswer = keyboard.next().charAt(0);
System.out.println();
if (getAnswer == 'y' || getAnswer == 'Y')
{
System.out.println("Stuff.");
test = 1;
}
else if( getAnswer == 'n' || getAnswer == 'N')
{
System.out.println("Other stuff.");
System.out.println();
}
If you absolutely have to use a switch:
char getAnswer = keyboard.next().charAt(0);
switch(getAnswer)
{
case 'y':
System.out.println("Stuff.");
test = 1;
break;
case 'n':
System.out.println("Other stuff.");
System.out.println();
break;
}
You can achieve the same thing in one line:
public static int getYN(String s) {
return ("yn YN".indrxOf(s) + 3) % 3;
}
Both upper and lower cases are handled, and the "not found" default value of 2 is handled by adding 3 (indexOf() returns -1 when the target is not found) and modulus divusion takes care of the capital letter indexes.
Fairly neat even if I do say so myself.
how come this java switch statement keeps telling me my statements are not statements
public void setConstant(float inNumGrade)
{
this.yourNumberGrade = inNumGrade;
switch (this.yourLetterGrade)
{
case 'A':
this.yourNumberGrade >= 0.90;
break;
case 'B':
this.yourNumberGrade >= .8;
break;
case 'C':
this.yourNumberGrade >= .7;
break;
case 'D':
this.yourNumberGrade >= .6;// not a statement
default:
} // end switch
}
I see what you are trying to do, but I think you are going around it the wrong way. What it seems like you are trying to do, is set the "letter grade" based on the switch, not the number grade! I think what you are really trying to do is this:
public void setGrades(float inNumGrade)
{
this.yourNumberGrade = inNumGrade;
if( this.yourNumberGrade >= 0.90)
this.yourLetterGrade = 'A';
else if(this.yourNumberGrade >=0.80)
this.yourLetterGrade = 'B';
else if (this.yourNumberGrade >=0.70)
this.yourLetterGrade= 'C';
else if (this.yourNumberGrade >=0.60)
this.yourLetterGrade= 'D';
else
this.yourLetterGrade= 'F';
}
You cannot switch on ranges in Java. If you want to do this with a switch, you'd have to do a switch(true), and then do case this.yourNumberGrade>=0.90:
As I expected, you misunderstand how a switch works. If you REALLY need to do this via switch(if/else/else if is better), you'd have to do it this way:
public void setGrades(float inNumGrade)
{
this.yourNumberGrade = inNumGrade;
switch(true)
{
case this.yourNumberGrade >= 0.90:
this.yourLetterGrade = 'A';
break;
case this.yourNumberGrade >=0.80:
this.yourLetterGrade = 'B';
break;
case this.yourNumberGrade >=0.70:
this.yourLetterGrade= 'C';
break;
case this.yourNumberGrade >=0.60:
this.yourLetterGrade= 'D';
break;
default:
this.yourLetterGrade= 'F';
break;
}//end switch
}
Because this.yourNumberGrade >= .6; isn't a valid statement like the compiler is telling you. This would be a valid statement:
b = this.yourNumberGrade >= .6;
-- or --
this.yourNumberGrade = .6;
It depends on what you are trying to accomplish.
What exactly are you trying to do? >= is comparison NOT assignment that is why you get the error...just remove > in all places.
Eric explained nicely how to do what you seem to be trying to accomplish, but let me clear up where you went wrong.
A switch/case structure compares a given variable (the switch argument) to possible values (the case arguments) and then executes the code between the matching case statement and the next break statement (or, if the language does not support fall-through, before the next case statement).
What you're trying to do is not to compare a variable to constant expressions, but to compare a variable against conditions. An if/elseif structure would probably be a cleaner way to express it:
if (this.yourNumberGrade >= 0.90) {
this.yourLetterGrade = 'A';
} else if (this.yourNumberGrade >= 0.80) {
this.yourLetterGrade = 'B';
} else if (this.yourNumberGrade >= 0.70) {
this.yourLetterGrade = 'C';
} else if (this.yourNumberGrade >= 0.60) {
this.yourLetterGrade = 'D';
} else { // you left the default out, but I assume this will be an F for Failed
this.yourLetterGrade = 'F';
}
If you want it shorter, you could try experimenting with the ternary operator like so:
this.yourLetterGrade = (
this.yourNumberGrade >= 0.90 ? 'A' : (
this.yourNumberGrade >= 0.80 ? 'B' : (
this.yourNumberGrade >= 0.70 ? 'C' : (
this.yourNumberGrade >= 0.60 ? 'D' : 'F'
)
)
)
)
As you can see, this costs you a LOT of readability, so if/else is probably the cleanest way to do it.
What Eric was trying to show you is a structure like this:
switch (true) { // We compare the boolean constant "true" to the case arguments
case this.yourNumberGrade >= 0.90:
// this is a boolean expression and evaluates either
// to "true" (matches the switch argument) or
// to "false" (does not match the switch argument)
this.yourLetterGrade = 'A';
break;
case this.yourNumberGrade >= 0.80:
this.yourLetterGrade = 'B';
break;
case this.yourNumberGrade >= 0.70:
this.yourLetterGrade = 'C';
break;
case this.yourNumberGrade >= 0.90:
this.yourLetterGrade = 'D';
break;
default:
// This is executed if none of the case arguments evaluate
// to the value of the switch argument.
this.yourLetterGrade = 'F';
// No break needed, because the end of the switch structure follows:
}
I hope that clears it up for you. You probably have to pay more attention to the exact semantics of the structures you are trying to use. These structures are very similar in most languages.
For kicks and giggles, you could even do it with an array:
// Our letter grades in ascending order (from bad to good).
String letterGrades[] = {'F','D','C','B','A'};
// Our number grade is in the range [0.0;1.0]. As floating point numbers are
// too precise for indexes, we want to round them down to the cut-off
// (0.9, 0.8, etc) and turn them into integer values we can use as array indices.
int gradeIndex = (int) Math.floor(this.yourNumberGrade*10);
// The lowest cut-off is 0.6, so we can treat everything lower than that the same
gradeindex = gradeindex - 5;
gradeIndex = Math.max(gradeIndex, 0);
// With Math.max we have ensured that no index can be lower than 0, now we need
// to make sure that no index is larger than the largest index in our array
// (which by definition is equal to the array's length (i.e. number of elements)
// minus 1 (because the lowest index is 0, an array of e.g. size 4 has the
// indices 0,1,2,3, but lacks an index 4 -- better get used to it, that's how
// programmers count, too).
gradeIndex = Math.min(gradeIndex, letterGrades.length-1);
// Now that our index is clean and guaranteed to be within range, we can use it
// to look up the letter grade:
this.yourLetterGrade = letterGrades[gradeIndex];
Without comments and with a few shorthands, this is even shorter:
// Grades are as follows: A: 90%+, B: 80%+, C: 70%+, D: 60%+, F: <60%
String letterGrades[] = {'F','D','C','B','A'};
int gradeIndex = Math.min(
Math.max(0, (int) Math.floor(this.yourNumberGrade*10) - 5),
letterGrades.length-1
);
this.yourLetterGrade = letterGrades[gradeIndex];
Note that this makes, however, less clear, where the exact cut-off points for the letter grades are, which is why it needs comments. Also, you'll have a problem if the cut-offs change for any reason (e.g. A: 85%+ or F: <66.6%). You could still adjust the calculation (the Math.floor(this.yourNumberGrade*10)-5 part), but this will make it even harder to follow and won't help if the grades aren't merely gradual. For traditional systems, however, it's a quick and easy way to do it.
You are only doing a comparison which isn't a valid statement in this context.
You probably mean to do an assignment
replace ">=" with "=" if that's what you want to accomplish.
The problem is that you are making a comparison and not assigning the the value. Perhaps you could do something like this:
public void setConstant(float inNumGrade)
{
this.yourNumberGrade = inNumGrade;
switch (this.yourLetterGrade)
{
case 'A':
this.yourNumberGrade = 0.90;
break;
case 'B':
this.yourNumberGrade = .8;
break;
case 'C':
this.yourNumberGrade = .7;
break;
case 'D':
this.yourNumberGrade = .6;
default:
} // end switch
}
This would actually assign the value to "yourNumberGrade. However this would only be the lower limit of the grade. It might be better to make it where you substitute the "yourNumberGrade" for "yourLetterGrade" and have it determine the letter grade based on the number grade...
You must add a break; inside of each case block.
switch(this.grade){
case 'A':
System.out.println("You got an A");
break;
default:
System.out.println("INVALID GRADE");
break;}