I was doing some some Java homework with my friend. The instructor wants him to write a Java program to translate an integer input into a numeric grade. 100-90 = A and so on. The only catch is that he must use a switch statement. He must also:
Include a case in your switch statement that will display a polite
error message if the user enters any number less than 0 or greater
than 100."
Originally I thought of this...
import java.util.Scanner;
public class grade
{
public static void main(String[] args)
{
int ng;//number grade
String lg = "";//letter grade
System.out.println("enter grade");
Scanner in = new Scanner(System.in);
ng = in.nextInt();
switch (ng/10)
{
case 10:
case 9:
lg = "A";
break;
case 8:
lg = "B";
break;
case 7:
lg = "C";
break;
case 6:
lg = "D";
break;
default:
lg = "F";
break;
}
System.out.println("You got an " + lg);
}
}
This isn't perfect because it allows values over 100 and below 0, but I am trying to avoid typing out every integer from 100-0. This seems like a ridiculous use of a switch statement and I can't imagine why a college professor would teach it, other than to illustrate the DRY principle.
Is there a better way that still uses the switch statement, but doesn't type every int from 100-0?
You could always add some minor complexity to your switch expression to make the cases simpler; this will calculate 90-100 as 10, 80-89 as 9 and so on, 101 and above will become 11 and above, and every input below 0 will become 0 or negative so they'll fall under default;
switch ((ng-ng/100+10)/10)
{
case 10:
lg = "A";
break;
case 9:
lg = "B";
break;
case 8:
lg = "C";
break;
case 7:
lg = "D";
break;
case 6: case 5: case 4:
case 3: case 2: case 1:
lg = "F";
break;
default:
System.out.println("Polite Error");
lg = "";
}
Yeah, no way in hell you would want to actually use a switch statement for this lol. But the way you've suggested is about the best way I can think of to do it.
I would make the default be for the error scenario though, because that could any integer less than 0 or over 100. Between 0 and 100, at least you have a finite number of cases (though you'll have to repeat the "F" case several times).
Nice use of integer division ;)
Okay, well this code officially embarrasses me and makes me cry. But here, just using switch statements.
import java.util.Scanner;
public class grade
{
public static void main(String[] args)
{
int ng;//number grade
String lg = "";//letter grade
boolean error = false;
System.out.println("enter grade");
Scanner in = new Scanner(System.in);
ng = in.nextInt();
switch (ng/10)
{
case 10:
switch (ng)
{
case 100:
lg = "A";
break;
default:
error = false;
break;
}
break;
case 9:
lg = "A";
break;
case 8:
lg = "B";
break;
case 7:
lg = "C";
break;
case 6:
lg = "D";
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
lg = "F";
break;
default:
error = true;
break;
}
if (error) {
System.out.println("Sorry, the grade must be between 0 and 100");
} else {
System.out.println("You got an " + lg);
}
}
}
Blech.
How about:
String lg = null;
switch (ng/10)
{
case 10:
if (ng > 100) {
// polite error
break;
}
case 9:
lg = "A"
break;
case 8:
lg = "B";
break;
case 7:
lg = "C";
break;
case 6:
lg = "D";
break;
default:
if (ng < 0) {
// polite error
break;
}
lg = "F";
break;
}
After the switch you'd have to check if a grade were set or not.
if (lg == null) {
System.out.println("The input score was > 100 or < 0");
} else {
System.out.println("You got an " + lg);
}
Related
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;
This question already has answers here:
Switch without break
(7 answers)
Closed 6 years ago.
I have this simple code. An integer which value is 0 and a null String. Simple enough. Yet when I run the program it prints "a" instead of "z". I don't know where's the problem and what am I missing.
public static void main(String[] args) {
int classCode = 0;
String classString = null;
switch(classCode) {
case 0:
classString = "z";
case 10:
classString = "a";
break;
case 11:
classString = "b";
break;
case 20:
classString = "c";
break;
case 21:
classString = "d";
break;
case 30:
classString = "e ";
break;
case 31:
classString = "f";
break;
}
System.out.println(classString);
}
You have forgotten to put a break after the first case.
switch(classCode) {
case 0:
classString = "z";
// missing a break here
case 10:
classString = "a";
break;
import java.util.Scanner;
public class LetterGrade
{
public static void main(String[] args)
{
char grade;
String input;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter grade awarded");
input = keyboard.nextLine();
grade = input.charAt(0);
switch (grade)
{
case 'A':
System.out.println("Grade was between " + 89.5 - 100);
break;
case 'B':
System.out.println("Grade was between " + 79.5 - 89.45);
break;
case 'C':
System.out.println("Grade was between " + 69.5 - 79.49);
break;
case 'D':
System.out.println("Grade was between " + 59.5 - 69.49);
break;
case 'F':
System.out.println("Grade was below " + 59.5);
break;
System.out.println("Invalid grade inputted ");
}
}
}
4 errors found:
File: C:\Users\Raj\Downloads\Java\LetterGrade.java [line: 19]
Error: The operator - is undefined for the argument type(s) java.lang.String, int
File: C:\Users\Raj\Downloads\Java\LetterGrade.java [line: 22]
Error: The operator - is undefined for the argument type(s) java.lang.String, double
File: C:\Users\Raj\Downloads\Java\LetterGrade.java [line: 25]
Error: The operator - is undefined for the argument type(s) java.lang.String, double
I fixed the big errors i had, sorry about that. I really wasn't thinking straight and I understand i need to read more, which i will be doing tonight, but I'm have a different error now.
Problems:
1. grade = keyboard.next.Int(); should be grade = keyboard.nextInt();
2. Case A;
a. Case should be case
b. What is A you switch an int but there is no variable A that
holds any int value. Also if you mean the char A the you should
change it to 'A'
You need a : instead of ;after case. So something like case 'A':
3. switch (grade); remove the ;. Change it to switch (grade)
4. Not sure about this Any other character; Hopefully its meant to be a comment
First Issue:
grade = keyboard.next.Int();
change to
grade = keyboard.nextInt();
Second Issue:
your The switch Statement is clearly wrong
for example
switch (grade); <--- wrong
{
Case A; <--- wrong
your grade is type int but your case has type char
Case in wrong, you should have case
Look at this sample as your blue print
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
Source of Code and Read more about Switch Statement
There should not be a semi-colon at the end of line 13. (The "switch" line).
Once you have fixed that, you will then see that the syntax of the "case" clauses is wrong.
And "any other character" is nonsense from the Java perspective. (I'm surprised that the Java compiler didn't throw a house-brick at you!)
I'm not sure what's wrong with what I'm doing.
You are trying to write Java without bothering to learn it properly. That is wrong on many levels.
I recommend that you read the Oracle Java Tutorial. For this example, read the Switch Statement page.
So I am making a program in Java on a BlueJ environment that computes Binary expansion. However, I can't seem to figure out how to add powers more than 9 in the output.
If I have an input power of anything more than 9 the program goes haywire, presumably because there are no cases after 9.
Also, I personally feel my program in general is extremely inefficient but I just did it this morning and this was the first approach I saw, so if you see a way to make it more efficient than using switch case, that'd be great too.
This is my code so far. It's not all mine, but I'm not sure if intellectual property and stuff applies on here, so just putting it out there.
import java.util.*;
class Binomial_Theorem_Expansion
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of x in (x+a)^n");
int x=s.nextInt();
System.out.println("Enter the value of a in (x+a)^n");
int a=s.nextInt();
System.out.println("Enter the value of n in (x+a)^n");
int n=s.nextInt();
System.out.println ("The expanded answer is");
int r=0;
int powx=n;
while (r<=n)
{
long nCr=calculatenCr(n,r);
if(nCr!=-1)
{
double y=Math.pow((double)x,(double)n-r);
double z=Math.pow((double)a,(double)r);
switch (powx)
{
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
case 2: System.out.print ("("+nCr*y*z+"x\u00B2");
break;
case 3: System.out.print ("("+nCr*y*z+"x\u00B3");
break;
case 4: System.out.print ("("+nCr*y*z+"x\u2074");
break;
case 5: System.out.print ("("+nCr*y*z+"x\u2075");
break;
case 6: System.out.print ("("+nCr*y*z+"x\u2076");
break;
case 7: System.out.print ("("+nCr*y*z+"x\u2077");
break;
case 8: System.out.print ("("+nCr*y*z+"x\u2078");
break;
case 9: System.out.print ("("+nCr*y*z+"x\u2079");
break;
case 10: System.out.print ("("+nCr*y*z+"x\u2071\u00B2");
break;
}
switch (r) {
case 0: System.out.print (")");
break;
case 1: System.out.print ("y"+")");
break;
case 2: System.out.print ("y\u00B2"+")");
break;
case 3: System.out.print ("y\u00B3"+")");
break;
case 4: System.out.print ("y\u2074"+")");
break;
case 5: System.out.print ("y\u2075"+")");
break;
case 6: System.out.print ("y\u2076"+")");
break;
case 7: System.out.print ("y\u2077"+")");
break;
case 8: System.out.print ("y\u2078"+")");
break;
case 9: System.out.print ("y\u2079"+")");
break;
}
r++;
if (r<=n)
{
System.out.print ("+");
}
powx--;
}
}
}
public static long calculatenCr(int n,int r)
{
long res=1;
if(n>=r)
{
res=getFact(n)/(getFact(n-r)*getFact(r));
return res;
}
else return -1;
}
public static long getFact(int n)
{
long f=1;
for(int i=n;i>=1;i--)
{
f*=i;
}
return f;
}
}
Thanks for any constructive input. :)
presumably because there are no cases after 9.
Your code is using UNICODE superscript characters, and the cases that you have cover only numbers zero through ten for x and zero through nine for y.
You can fix this by defining a method that produces a superscript UNICODE conversion of a multidigit number, and calling it from both places where you need to produce such representation:
switch (powx) {
case 0: System.out.print ("("+nCr*y*z);
break;
case 1: System.out.print ("("+nCr*y*z+"x");
break;
default: System.out.print ("("+nCr*y*z+"x"+toSuperscript(powx));
break;
}
The other switch (i.e. switch (r)) should be converted in a similar way.
You can implement String toSuperscript(int n) by producing a decimal representation of n, and then replacing '0' with '\u2070', '1' with '\u00B9', and so on.
I only need help with the input part. If the user inputs a number I need the program to read and output a case that equals the number that was input.
//This program will display the months of the year
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
int month;
System.out.println("Please enter a Month Number: ");
month = (int) System.in.read(); //Get an integer
switch (month) {
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;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}
Try using the Console class instead: http://docs.oracle.com/javase/6/docs/api/java/io/Console.html to obtain user input, then convert the String to a number with Integer.parseInt(String)
Also, be aware that the next version of Java (8) will support Strings in case blocks.
class vehicle
{
int passengers;
int fuelcap;
int mpg;
}
import java.io.*;
class Vehicle_Demo
{
public static void main (String args[]) throws java.io.IOException
{
vehicle obj1 = new vehicle();
obj1.passengers=12;
obj1.fuelcap=9;
obj1.mpg=78;
System.out.println(obj1.passengers, obj1.fuelcap, obj1.mpg);
}
}
You can use Scanner to read your System.in
Scanner input = new Scanner(System.in);
month = input.nextInt();
Output:
Please enter a Month Number:
1
January
See related
Edit:
as noahz pointed out there is a Console class that covers the same functionality. For an idea of the difference between the two, read this.
Try to use TextIO Input Functions
This is better than scanner input
You need to compile TextIO.java fist as a prerequisite so that TextIO.class must be found in the same folder.
use this input function instead:
month = TextIO.getChar();
Please let me know if you have problems on this method.
Thanks!
Correct me if I'm wrong, but I'm pretty sure it will still work with "system.in.read". You're switch cases do not have single quotes around the input you want to be processed. If you want case one to be run when you type '1' your case should be case '1', not case 1.
There problem here was Java have cast a character to an integer, therefore you get an ASCII value.
For instance, when you type 5 you've got 53 in ASCII. Check it taking the variable value in System.out.println();
I've tried to solve that changing month to a char type and then passing a char value to the switch control. But the problem is, getting System.in.read(); method you just can get a single character. At last you just can select between 1 to 9.
I suspect the solution is using a buffer reader. Until then, I leave you here my code:
public class MonthsOfTheYear {
public static void main(String[] args)
throws java.io.IOException{
char month;
System.out.println("Please enter a Month Number: ");
month = (char) System.in.read(); //Get an integer
//System.out.println("Actual value of :" + month);
switch (month) {
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;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
/*case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;*/
default: System.out.println("Invalid Month");
break;
}
System.out.println();
}
}