Why can't the String variable be printed in this program? [duplicate] - java

This question already has answers here:
Why can't I initialize a variable inside a switch in Java?
(6 answers)
Closed 2 years ago.
This code is for the purpose of changing months to the corresponding letter codes.
Here is my code I wrote so far:
public static void main (String[ ] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter month number. [1..12] --> ");
int month = input.nextInt();
String MonthString;
switch (month)
{
case 1 : MonthString = "ZS"; break;
case 2 : MonthString = "CN"; break;
case 3 : MonthString = "YH"; break;
case 4 : MonthString = "MT"; break;
case 5 : MonthString = "CL"; break;
case 6 : MonthString = "SS"; break;
case 7 : MonthString = "WM"; break;
case 8 : MonthString = "WY"; break;
case 9 : MonthString = "SH"; break;
case 10 : MonthString = "YJ"; break;
case 11 : MonthString = "XG"; break;
case 12 : MonthString = "HZ"; break;
default : System.out.print("This is not a valid month number.");
}
System.out.println(MonthString);/*This is where it won't compile*/
}

You need to initialize MonthString first:
String MonthString = null;

default: MonthString = "This is not a valid number";
you need to assign the value in the default of your switch statement, not print it out since it's going to get printed after the switch/case is over.

You need to put something on String monthString = ""; first.
Note lowercase and uppercase letters in a variable boot :
When you initialize a variable it should be initialized as follows:
String firstExample= "Hello world"; and not : String FirstExample= "Hello world"; , Classes are given names with capital letters.
public static void main (String[ ] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter month number. [1..12] --> ");
int month = input.nextInt();
String monthString = "";
switch (month)
{
case 1 : monthString = "ZS"; break;
case 2 : monthString = "CN"; break;
case 3 : monthString = "YH"; break;
case 4 : monthString = "MT"; break;
case 5 : monthString = "CL"; break;
case 6 : monthString = "SS"; break;
case 7 : monthString = "WM"; break;
case 8 : monthString = "WY"; break;
case 9 : monthString = "SH"; break;
case 10 : monthString = "YJ"; break;
case 11 : monthString = "XG"; break;
case 12 : monthString = "HZ"; break;
default : System.out.print("This is not a valid month number.");
}
System.out.println(monthString);
}
}
Output :
Enter month number. [1..12] --> 1
ZS

Related

Switch choosing wrong int case [duplicate]

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;

why variable have to be initialized?

here i tried to get output month by inputting month number but why i am having error
- "monthString" mightn't have been initialized ?
- and why i am not getting output string from " monthString "?
why monthString have to be initialized ?
import java.util.Scanner;
public class SwitchClass {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.printf(" when did u born ? ");
int monthNumber = input.nextInt();
String monthString ;
switch (monthNumber)
{
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;
}
System.out.println(monthString); }
}
What if monthNumber is not between 1 and 12? In that case, monthString won't be initialized. You should give it some default value when you declare it :
String monthString = null; // or ""
It would be a good idea to add a default case to your switch statement.
Example:
switch (monthNumber) {
case 1: monthString = "January";
break;
//other cases...
default: monthString = "Invalid Month Number";
break;
}
This way if monthNumber is not 1-12 then there is still a default case for the switch statement to flow to.
May be this link will help to get proper understanding.
http://stackoverflow.com/questions/5478996/should-java-string-method-local-variables-be-initialized-to-null-or
monthString is a local variable within main(), therefore, it must be initialized to prevent the compiler error.
If monthString were a Class variable then it does not have to be initialized explicitly.
You can do this by moving monthString outside of main() and declare it as:
static String monthString;
Because the designer of Java language believes it made more sense for it to be! Codes are easier to read when variables are initialised. A statement String foo; feels non-deterministic because you have to guess what's the default value of String is whereas String foo = null; is more deterministic.
To give you a more obvious example, consider this:
int x;
Int y;
Can you very quickly guess what the default values are? You probably have to pause for a few second to realize x is probably 0 and y is probably null
Local variables MUST always be initialized before use.
For Java 6, the compiler doesn't consider the "Incomplete" initialization of variables within flow control blocks and try-catch blocks. The initialization must be done for all cases:
If - else:
String s;
int a = 10;
if(a > 5){
s = "5";
}else{
System.out.println("");
}
System.out.println(s); // error if s isn't initialized within both if and else blocks
While loop:
String s;
int a = 10;
while(a > 0) {
s= ">0";
a--;
}
System.out.println(s);// error if s isn't initialized outside the while
Try-Catch block:
String s;
try {
s = "";
} catch (Exception e) {}
System.out.println(s);// error if s isn't initialized within both try and catch blocks
Switch block:
String s;
int a = 10;
switch (a) {
case 10:
s="10";
break;
default:
break;
}
System.out.println(s);// error if s isn't initialized all cases, default case included
Initialize the variable before the switch and all will be fine.
String monthString = "";

I'm having an "Error: Syntax error on token(s), misplaced construct(s)". Where is my error?

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.

Switch Statement Reverse

Okay so i'm trying to complete this project for school and it is asking me to make a switch statement of the months. So if a user enters 1 it will print out January and so on... I get this error where it says: cannot find symbol - variable January
import java.util.*;
/**
* Outputs the number on a month name entered by the user.
*
* #author Jack
* #version 1a
*/
public class MonthSwitchReverse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int monthString;
String month;
System.out.println(" Jan = 1 / Feb = 2 / March = 3 / April = 4 / MAy = 5 / June = 6");
System.out.println(" July = 7 / Aug = 8 / Sep = 9 / Oct = 10 / Nov = 11 / Dec = 12");
System.out.print("Choose a month above and the system will print out the number assigned to that month: ");
month = in.next();
switch (month) {
case "January": monthString = 1;
break;
case "February": monthString = 2;
break;
case "March": monthString = 3;
break;
case "April": monthString = 4;
break;
case "May": monthString = 5;
break;
case "June": monthString = 6;
break;
case "July": monthString = 7;
break;
case "August": monthString = 8;
break;
case "September": monthString = 9;
break;
case "October": monthString = 10;
break;
case "November": monthString = 11;
break;
case "December": monthString = 12;
break;
default: monthString = 404;
break;
}
System.out.println(monthString);
}
}
EDIT: I fixed it. Thanks for your help.
Since you are passing an integer to switch , That each case should be an int value.
For example
case 1: monthString = "1";
case 2: monthString = "2";
And same for remaining all.
recommending to read : Switch in java.

What's wrong with my code? Zeller's Congruence algorithm code

What's wrong with my code? For some reason I keep on getting the day off by one day? For example, today is the 26th of 2013 and it's a Tuesday, but the program tells me it's a Wednesday. I am using Zeller's Congruence algorithm.
import javax.swing.JOptionPane;
public class zeller {
public static void main(String[] args) {
String yearString = JOptionPane.showInputDialog("Enter the year:");
int year = Integer.parseInt(yearString);
String monthString = JOptionPane.showInputDialog("Enter the month (3-12)(January and Feburary are 13 and 14):");
int month = Integer.parseInt(monthString);
String dayString = JOptionPane.showInputDialog("Enter the day 1-31: ");
int day = Integer.parseInt(dayString);
switch (month) {
case 13: monthString = "January";
break;
case 14: 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;
}
int j = year / 100;
int k = year % 100 ;
double h = (day + ((26*(month + 1)) / 10) + k + (k / 4) +(j / 4) + (5 * j)) % 7;
int h1 = (int)h;
switch (h1) {
case 0: dayString = "Saturday";
break;
case 1: dayString = "Sunday";
break;
case 2: dayString = "Monday";
break;
case 3: dayString = "Tuesday";
break;
case 4: dayString = "Wednesday";
break;
case 5: dayString = "Thursday";
break;
case 6: dayString = "Friday";
break;
default: monthString = "Invalid month";
break;
}
System.out.println("Day of the week is: " + dayString);
}
}
The months Jan and Feb are counted as the 13th and 14th month of the previous year, so
if you want the user to enter the actual months of 1 or 2 for Jan or Feb you could add code like this:
if (month == 1 ){
month = 13;
year -=1;
}
else if (month == 2) {
month = 14;
year -=1;
}
You need to modify the year if it is January or February. Explanation on wikipedia:
One can readily see that, in a given year, March 1 (if that is a
Saturday, then March 2) is a good test date; and that, in a given
century, the best test year is that which is a multiple of 100. Zeller
used decimal arithmetic, and found it convenient to use J and K in
representing the year. But when using a computer, it is simpler to
handle the modified year Y, which is Y - 1 during January and
February:
I modified your code as follows and it works:
import javax.swing.JOptionPane;
public class zeller {
public static void main(final String[] args) {
String yearString = JOptionPane.showInputDialog("Enter the year:");
int year = Integer.parseInt(yearString);
String monthString =
JOptionPane.showInputDialog("Enter the month (3-12)(January and Feburary are 13 and 14):");
int month = Integer.parseInt(monthString);
String dayString = JOptionPane.showInputDialog("Enter the day 1-31: ");
int day = Integer.parseInt(dayString);
switch (month) {
case 14:
year--;
monthString = "January";
break;
case 13:
year--;
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;
}
int j = year / 100;
int k = year % 100;
double h = (day + ((13 * (month + 1) / 5)) + k + (k / 4) + (j / 4) + (5 * j)) % 7;
int h1 = (int) h;
switch (h1) {
case 0:
dayString = "Saturday";
break;
case 1:
dayString = "Sunday";
break;
case 2:
dayString = "Monday";
break;
case 3:
dayString = "Tuesday";
break;
case 4:
dayString = "Wednesday";
break;
case 5:
dayString = "Thursday";
break;
case 6:
dayString = "Friday";
break;
default:
monthString = "Invalid month";
break;
}
System.out.println("Day of the week is: " + dayString);
}
}
From Wikipedia,
In this algorithm January and February are counted as months 13 and 14 of the previous year. E.g. if it is February 2, 2010, the algorithm counts the date as the second day of the fourteenth month of 2009 (02/14/2009 in DD/MM/YYYY format).
So there is technically nothing wrong with your code; putting in 02/26/2013 (today) as the 26th day of the 14th month of 2013 is actually calculating the day of the week of 02/26/2014.

Categories

Resources