Adding user input to nested switch cases - java

I want the user to enter their grade (ex. A+) and I would give them the result. I need help adding the user input into the console because I am really confused as to how I would add it in nested cases.
My code:
public class SwitchCase {
public static void main(String[] args) {
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() > 1)
{
modifier = plusorminus.charAt(1);
}
java.util.Scanner input=new java.util.Scanner(System.in);
switch(mark)
{
case 'A':
switch(modifier)
{
case '+': System.out.println("Your grade is 90-99.99%"); break;
case '-': System.out.println("Your grade is 90-84.99%"); break;
default: System.out.println("Your grade is 85-89.99%"); break;
}
break;
case 'B':
switch(modifier)
{
case'+': System.out.println("Your grade is 77.00 - 79.99%"); break;
case'-': System.out.println("Your grade is 70.00 - 72.99%"); break;
default: System.out.println("Your grade is 73.00 - 76.99%"); break;
}
break;
case 'C':
switch(modifier)
{
case'+': System.out.println("Your grade range is 67.00 - 69.99%"); break;
case'-': System.out.println("Your grade range is 60.00 - 62.99%"); break;
default: System.out.println("Your grade range is 63.00 - 66.99%"); break;
}
break;
case 'D':
switch(modifier)
{
case'+': System.out.println("Your grade range is 55.00 - 59.99%"); break;
case'-': System.out.println("-"); break;
default: System.out.println("Your grade range is 50.00 - 54.99%"); break;
}
break;
case 'F':
switch(modifier)
{
default: System.out.println("Your grade range is 0.00-49.99%"); break;
}
break;
}
input.close();
}
}

input.nextLine() will return a String that you can assign to a variable. You are using char in your switch statement, so you will need to get the first letter of that String to allow this.
java.util.Scanner input = new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char mark = userInputString.charAt(0);

Another solution, instead of steven35, is do in that way (this way, you can integrate from what you already had done)
public class SwitchCase {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
System.out.println("Input a mark");
String line = scanIn.nextLine();
if (line.length()>2){
System.out.println("ex: +a / -a / a");
return;
}
char[] cA = line.substring(1, 2).toUpperCase().toCharArray();
char[] cB = line.substring(0, 1).toUpperCase().toCharArray();
char mark = cA[0];
char modifier = cB[0];
System.out.println(" INPUT: "+modifier+mark);
switch(mark)
{
case 'A':
switch(modifier)
{
case '+': System.out.println("Your grade is 90-99.99%"); break;
case '-': System.out.println("Your grade is 90-84.99%"); break;
default: System.out.println("Your grade is 85-89.99%"); break;
}
break;
case 'B':
switch(modifier)
{
case'+': System.out.println("Your grade is 77.00 - 79.99%"); break;
case'-': System.out.println("Your grade is 70.00 - 72.99%"); break;
default: System.out.println("Your grade is 73.00 - 76.99%"); break;
}
break;
case 'C':
switch(modifier)
{
case'+': System.out.println("Your grade range is 67.00 - 69.99%"); break;
case'-': System.out.println("Your grade range is 60.00 - 62.99%"); break;
default: System.out.println("Your grade range is 63.00 - 66.99%"); break;
}
break;
case 'D':
switch(modifier)
{
case'+': System.out.println("Your grade range is 55.00 - 59.99%"); break;
case'-': System.out.println("-"); break;
default: System.out.println("Your grade range is 50.00 - 54.99%"); break;
}
break;
case 'F':
switch(modifier)
{
default: System.out.println("Your grade range is 0.00-49.99%"); break;
}
break;
}
//input.close();
}
}

Related

Taking int input and parsing into char

So my main got deleted 2 days ago and my teacher helped me a bit with the switch code. I rebuilt the code yesterday and he was away yesterday and could not help me.
public static void main(String[] args) throws InterruptedException {
do {
try {
System.out.println("Enter your birthYear");
birthYear = Integer.parseInt(input.next());
int length = String.valueOf(birthYear).length();
System.out.println(length);
if (length != 4) {
lengthTest = false;
System.out.println("Invalid Choice");
} else {
lengthTest = true;
}
test = true;
} catch (Exception e) {
System.out.println("Invalid Choice");
}
} while (test == true ^ lengthTest != false);
do {
System.out.println("Please enter a number between 1-4 \n"
+ "1 = AreaOfTriangle \n" +
"----------------------------------\n" +
"2 = HoursToDaysAndHours Calculator \n" +
"---------------------------------- \n" +
"3 = CelciusToFahrenheit Calculator \n" +
"----------------------------------\n" +
"4 = BirthdayGame \r\n" +
"----------------------------------");
try {
choice = Integer.toString(input.nextInt()).charAt(0);
System.out.println(choice);
switch (choice) {
case 1:
aOT.areaOfTriangle();
break;
case 2:
hTDAH.hoursToDaysAndHours();
break;
case 3:
cTF.celciusToFahrenheit();
case 4:
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}
}catch (Exception e) {
System.out.println("Invalid Awnser");
}
} while (repeat == true);
}
My problem is in my switch case i want to be able to use int's and Char's at the same time. For example i want to use e to exit and and the 4 numbers
You can try to use String as an input paramenter, then any int value or char will be readed correctly without necessity to convert them:
try {
String choice = input.next();
System.out.println(choice);
switch (choice) {
case "1":
aOT.areaOfTriangle();
break;
case "2":
hTDAH.hoursToDaysAndHours();
break;
case "3":
cTF.celciusToFahrenheit();
case "4":
System.out.println("Code not implemented");
break;
case "e":
repeat = false;
break;
default:
System.out.println("");
break;
}
You can't use int and chars at the same time, as you can only use one variable and a variable has to have a type, but:
If you cast a char or Character to int you get values. For example ((int) 'e') evaluates to 101 if I am not mistaken. (Try System.out.println((int) 'e'));
So in your case, you can switch over int values and detect for 1,2,3,4 and 101.
Your default should also throw an exception and you are fine.
Happy Coding
You could just use the char representations of the digits 1-4:
char choice = input.next().charAt(0);
switch (choice) {
case '1':
aOT.areaOfTriangle();
break;
case '2':
hTDAH.hoursToDaysAndHours();
break;
case '3':
cTF.celciusToFahrenheit();
case '4':
System.out.println("Code not implemented");
break;
case 'e':
repeat = false;
break;
default:
System.out.println("");
break;
}

error in switch statement in java eclipse

this is the code-
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner kb=new Scanner(System.in);
System.out.println("enter a four digit number");
int number=kb.nextInt();
int digit2=number;
switch (digit1)
{
case 1: System.out.println("One");break;
case 2: System.out.println("Two");break;
case 3: System.out.println("Three");break;
case 4: System.out.println("Four");break;
case 5: System.out.println("Five");break;
case 6: System.out.println("Six");break;
case 7: System.out.println("Seven");break;
case 8: System.out.println("Eight");break;
case 9: System.out.println("Nine");break;
case 0: System.out.println("Zero");break;
default: System.out.println("");break;
}
switch (digit2)
{
case 1: System.out.println("One");break;
case 2: System.out.println("Two");break;
case 3: System.out.println("Three");break;
case 4: System.out.println("Four");break;
case 5: System.out.println("Five");break;
case 6: System.out.println("Six");break;
case 7: System.out.println("Seven");break;
case 8: System.out.println("Eight");break;
case 9: System.out.println("Nine");break;
case 0: System.out.println("Zero");break;
default: System.out.println("");break;
}
}
}
And this error is coming
2 errors
sh-4.3$ javac HelloWorld.java
HelloWorld.java:10: error: cannot find symbol
switch (digit1)
^
symbol: variable digit1
location: class HelloWorld
HelloWorld.java:10: error: illegal start of type
switch (digit1)
^
2 errors
pls help me
You have not defined a variable named digit1.
Here's some rough code to do what you want:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a four digit number");
String numStr = kb.next();
int number = 0;
try {
number = Integer.parseInt(numStr);
} catch (Exception e) {
System.out.println("Input was not a number!");
System.exit(1);
}
if (number < 1000) {
System.out.println("Number must be at least four digits!");
System.exit(1);
}
for (int digitNdx = 0; digitNdx < 4; digitNdx++) {
switch (numStr.charAt(digitNdx)) {
case '1':
System.out.println("One");
break;
case '2':
System.out.println("Two");
break;
case '3':
System.out.println("Three");
break;
case '4':
System.out.println("Four");
break;
case '5':
System.out.println("Five");
break;
case '6':
System.out.println("Six");
break;
case '7':
System.out.println("Seven");
break;
case '8':
System.out.println("Eight");
break;
case '9':
System.out.println("Nine");
break;
case '0':
System.out.println("Zero");
break;
default:
System.out.println("");
break;
}
}
}
}
Your code
Scanner kb = new Scanner(System.in);
System.out.println("enter a four digit number");
int number = kb.nextInt();
int digit2 = number;
switch (digit1) {
Error occur due to
here is no any variable assigned for digit1
Example
int digit1 = 5;
int digit2 = number;

Initialize An Array of Ints with Variables

I want to make an array of integer values that represent counters so I initialized it like this in my main method:
int [] counters = new int [7];
counters [countListAll] = 0;
counters [countEmployeeReport] = 0;
counters [countDivisionReport] = ;
counters [countSalaryReport] = 0;
counters [countRetirementReport] = 0;
counters [countMain] = 0;
counters [countOthers] = 0;
And now I have to pass this array to my menu() method so that I can increment each counter each time any of the options is chosen.
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [countListAll] ++;
break;
case 'E':
case 'e':
employeeReport();
counters [countEmployeeReport] ++;
break;
case 'D':
case 'd':
divisionReport();
counter [countDivisionReport] ++;
break;
case 'S':
case 's':
salaryReport();
counters [countSalaryReport] ++;
break;
case 'R':
case 'r':
retirementReport();
counters [countRetirementReport] ++;
break;
case 'Q':
case 'q':
counters [countMain] ++;
break;
else
{
menu();
countOthers++;
}
}
Am I initializing the array correctly and passing it into menu() method correctly? And am I allowed to increment the objects like that?
EDIT: I changed the code, and this is the new code
Main method:
int [] counters = new int [7];
counters [L] = 0;//listAll
counters [E] = 0;//employeeReport
counters [D] = 0;//divisionReport
counters [S] = 0;//salaryReport
counters [R] = 0;//retirementReport
counters [Q] = 0;//quit
counters [O] = 0;//others
Menu Method:
public static void menu(int [] counters)
{
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available. \nEnter 'E' to dislpay information on a particular employee. \nEnter 'D' to display division information. \nEnter 'S' to display salary information. \nEnter 'R' to display retirement information. \nEnter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = first.charAt(0);
if (first1 == 'L'|| first1 =='l'||first1 =='E'||first1 =='e'||first1 =='D'||first1 =='d'||first1 =='S'||first1 =='s'||first1 =='R'||first1 =='r'||first1 =='Q'||first1 =='q')
{
switch (first1)
{
case 'L':
case 'l':
listAll();
counters [L] ++;
break;
case 'E':
case 'e':
employeeReport();
counters[E]++;
break;
case 'D':
case 'd':
divisionReport();
counters [D]++;
break;
case 'S':
case 's':
salaryReport();
counters [S]++;
break;
case 'R':
case 'r':
retirementReport();
counters [R]++;
break;
case 'Q':
case 'q':
counters [Q]++;
break;
}
}
else
{
menu();
counters [O]++;
}
}
And FinalStats Method:
public static void finalStats(int [] counters)
{
System.out.println("Number of times listAll() was accessed from menu() is: " + counters[L]);
System.out.println("Number of times employeeReport() was accessed from menu() is: " + counters[E]);
System.out.println("Number of times divisionReport() was accessed from menu() is: " + counters[D]);
System.out.println("Number of times salaryReport() was accessed from menu() is: " + counters[S]);
System.out.println("Number of times retirementReport() was accessed from menu() is: " + counters[R]);
System.out.println("Number of times 'Quit' was chosen from menu() is: " + counters[Q]);
System.out.println("Number of times any other key was pressed in menu() is: " + counters[O]);
}
Yes, in general. There appears to be a bug with your countOthers logic. although nesting a switch with-in an if seems an odd choice, it would be much more readable with a simple if else-if chain (and you could use Character.toLowerCase(char) to handle mixed case. Something like,
if-else
public static void menu(int[] counters) {
System.out.println("You have accessed Menu()");
System.out.println("Enter 'L' for list of the employee data available.");
System.out.println("Enter 'E' to dislpay information on a particular employee.");
System.out.println("Enter 'D' to display division information.");
System.out.println("Enter 'S' to display salary information.");
System.out.println("Enter 'R' to display retirement information.");
System.out.println("Enter 'Q' to quit Menu and return to Main.");
Scanner scan = new Scanner(System.in);
String first = scan.next();
char first1 = Character.toLowerCase(first.charAt(0));
if (first1 == 'l') {
listAll();
counters[countListAll]++;
} else if (first1 == 'e') {
employeeReport();
counters[countEmployeeReport]++;
} else if (first1 == 'd') {
divisionReport();
counter[countDivisionReport]++;
} else if (first1 == 's') {
salaryReport();
counters[countSalaryReport]++;
} else if (first1 == 'r') {
retirementReport();
counters[countRetirementReport]++;
} else if (first1 == 'q') {
counters[countMain]++;
} else {
menu();
counters[countOthers]++; // <-- instead of countOthers++
}
}
switch-case
It is also possible to express the above if-else chain with switch-case and something like,
switch (Character.toLowerCase(first.charAt(0))) {
case 'l':
listAll();
counters[countListAll]++;
break;
case 'e':
employeeReport();
counters[countEmployeeReport]++;
break;
case 'd':
divisionReport();
counter[countDivisionReport]++;
break;
case 's':
salaryReport();
counters[countSalaryReport]++;
break;
case 'r':
retirementReport();
counters[countRetirementReport]++;
case 'q':
counters[countMain]++;
break;
default:
menu();
countOthers++;
}

Double Switch Method gone wild?

here is the method class
import java.util.Scanner;
public class Methods extends Basic {
Scanner keyboard = new Scanner(System.in);
public void Nome(){
String name = keyboard .nextLine();
System.out.println("what is your name");
switch(name){
case "john":
if(name.length() < 5){
System.out.println("your name is average");
break;
}
case "jason":
if(name.length()>5){
System.out.println("your name is not average");
break;
}
}
}
public void Dates(){
System.out.println("Enter a number and we will tell you what month it is:");
int jay = keyboard.nextInt();
switch(jay){
case 1:
System.out.println("january");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
default:
System.out.println("that aint in the month dawg");
}
}
}
and here is the main class
public class Basic {
public static void main(String args[]) {
Methods dateo = new Methods();
Methods nomalo = new Methods();
nomalo.Nome();
dateo.Dates();
}
}
so yea, I am a complete noob. and I am really struggling when learning Java :( A lot of my friends who started learning java can now make their own 2 games and here I am struggling with a basic concept...
so what is the problem in this code?
Edit - Forget what I said here. Your code is working fine aparently. Just put your
println before you make the scan.
System.out.println("what is your name");
String name = keyboard.nextLine();
So problems is you are reading the data from keyboard before you printed 'what is your name'
The Methods class does not need to extend Basic. the name method does not need to have switch case.
So the Methods class would look like below,
public class Methods {
Scanner keyboard = new Scanner(System.in);
public void name(){
System.out.println("what is your name");
String name = keyboard.nextLine();
if(name.length() < 5){
System.out.println("your name is average");
} else {
System.out.println("your name is not average");
}
}
public void Dates(){
System.out.println("Enter a number and we will tell you what month it is:");
int jay = keyboard.nextInt();
switch(jay){
case 1:
System.out.println("january");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
default:
System.out.println("that aint in the month dawg");
}
}
}

Need assignment idea

I need help with my assignment.I need to write class program that tranlates grade into grade point. If the grade have + like A+ it will increase the grade point by 0.3 and - will decrease by 0.3.
private static final double GradePoint = 0;
private static Scanner input;
public static void main(String [] args)
{
String grade ;
double GradePoint = 0;
System.out.print("Please enter your grade: ");
input = new Scanner(System.in);
grade = input.nextLine();
switch(grade)
{
case "A":
case "a": GradePoint = 4; break;
case "B":
case "b": GradePoint = 3; break;
case "C":
case "c": GradePoint = 2; break;
case "D":
case "d": GradePoint = 1; break;
case "F":
case "f": GradePoint = 0; break;
}
System.out.print("Your grade is: "+GradePoint);
}
public double getGradePoint(String grade)
{
return GradePoint;
}
What i dont understand is about how to use the method to calculate.I'm still beginner.
I have to use CLASS and method*public double getGradePoint(String grade)* to
return the grade point of grade entered.
You need to shift your entire code from main() to getGradePoint(String grade);
also your switch case switch(grade) will not work for values like "A+" as there are no such case that matches the string "A+"
I was bored and had nothing better to do so here :)
public class GradeCalculator
{
public static void main(String[] args)
{
System.out.print("Please enter your grade: ");
Scanner input = new Scanner(System.in);
String grade = input.nextLine().trim();
GradeCalculator calculator = new GradeCalculator();
double gradePoint = calculator.getGradePoint(grade);
System.out.print("Your grade is: " + gradePoint);
}
private double getGradePoint(String grade)
{
int score = getGradeScore(grade.charAt(0));
double modifier = 0;
if (grade.length() > 1)
{
modifier = getModifierValue(grade.charAt(1));
}
return score + modifier;
}
private int getGradeScore(char grade)
{
int score = 0;
switch (grade)
{
case 'A':
case 'a':
score = 4;
break;
case 'B':
case 'b':
score = 3;
break;
case 'C':
case 'c':
score = 2;
break;
case 'D':
case 'd':
score = 1;
break;
case 'F':
case 'f':
score = 0;
break;
}
return score;
}
private double getModifierValue(char modifier)
{
double value = 0;
switch (modifier)
{
case '+':
value = 0.3;
break;
case '-':
value = -0.3;
break;
}
return value;
}
}

Categories

Resources