why variable have to be initialized? - java

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 = "";

Related

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

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

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;

Java switch statement "case, default expected"

I'm trying to make a switch statement that prints out different messages based on whether the user inputs a 1, 2, or 3 but I keep getting errors. Just the small snippet of code below throws about a dozen errors which is probably some sort of record for me. :/
int menuSelection = keyboard.nextint;
switch
case 1: int menuSelection = "1";
break;
case 2: int menuSelection = "2";
break;
case 3: int menuSelection = "3";
break;
The error message is
"case, default, or '>' expected"
but I don't know what that means or how to fix it.
The syntax for your switch statement is incorrect. You need to switch on the variable and also add brackets to enclose your cases:
switch (menuSelection) {
case 1:
break;
case 2:
break;
case 3:
break;
}
Based on the below observations, the switch statement may look like this:
int menuSelection = keyboard.nextint;
String menuSelectionDisplay;
switch(menuSelection)
{
case 1:
menuSelectionDisplay = "1";
break;
case 2:
menuSelectionDisplay = "2";
break;
case 3:
menuSelectionDisplay = "3";
break;
default:
menuSelectionDisplay = "?";
break;
}
Switch statements are required to be surrounded by curly braces {}
It's considered a good idea to have a "default" clause within your switch statement. It acts as a catch-all that gets executed when none of the cases match. In the above example, if the value of menuSelection happened to be 4, the default clause would be executed.
The switch statement takes in one parameter, which is used to determine which case to run. Think of it as a series of if-else statements.
int value = 5;
switch(value)
{
case 5: System.out.println("Hello!"); break;
case 6: System.out.println("Bye!"); break;
default: System.out.println("Huh?"); break;
}
is equivalent to this:
if(value === 5)
{
System.out.println("Hello!");
}
else if(value === 6)
{
System.out.println("Bye!");
}
else
{
System.out.println("Huh?");
}
In your cases, you appear to be setting the value of an int to a String. That's invalid; you would need to either
Set the value of a String to be a String (String s = "1";), or
Set the value of an int to be an int (int i = 1;).
Finally, you cannot re-declare a variable's type multiple times within the code (that's having int menuSelection = keyboard.nextint; and int menuSelection = 3; in the same scope)
int menuSelection = keyboard.nextint;
switch (menuSelection) {
case 1:
menuSelection = "1";
break;
case 2:
menuSelection = "2";
break;
case 3:
menuSelection = "3";
break;
default:
break;
}

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.

Using throws java.io.IOException and getting System.in.read(); to access a case via an integer

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();
}
}

Categories

Resources