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;
Related
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
it's Java Starter here, so i was Coding my program which makes a Password, i used the Random Object to have a random Number that will choose what Letter comes or What number comes.
I keep getting the Numbers and the Symbols Only.. what i get is something Like this:
"9=9null=99" I don't understand Why there's a null. Java doesn't show me any problems with my code (Doesn't show Null Pointer exception.)
Here's My code:
package project.Secureword.com;
import java.awt.*;
import java.awt.event.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Random;
import javax.swing.*;
public class Main {
private static JFrame start;
private static TextField field;
private static String password;
private static String lastpass;
public static Settings passsettings;
public static Random r;
public static void main(String[] args) {
passsettings = new Settings();
passsettings.setIfDots(true);
passsettings.setIfLowercase(true);
passsettings.setIfNum(true);
passsettings.setIfUpprcase(true);
Settings.changerun();
start();
}
public static void start() {
Font a = new Font(null, Font.BOLD, 0);
Font size = a.deriveFont(20f);
JButton createPass = new JButton();
createPass.setText("<html> Click me to <br> Generate a Password! <html>");
createPass.setPreferredSize(new Dimension(100,100));
JLabel text = new JLabel();
text.setText("<html> Welcome to SECUREPASS! <br> An Extreme Strong Password Generator <br> Developed by OfficialCode");
text.setPreferredSize(new Dimension(150,150));
text.setFont(size);
field = new TextField(20);
field.setSize(new Dimension(50,50));
start = new JFrame("Secureword | Strong password Generator | Coded by OfficialCode");
start.setPreferredSize(new Dimension(390,390));
start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start.setLocationRelativeTo(null);
start.setLayout(new BorderLayout());
start.getContentPane().add(createPass, BorderLayout.WEST);
start.getContentPane().add(text, BorderLayout.PAGE_START);
start.getContentPane().add(field, BorderLayout.CENTER);
start.pack();
start.setVisible(true);
password = "";
createPass.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field.setText(null);
field.selectAll();
allrandom();
}});
}
public static void allrandom() {
String[] pass = new String[8];
Random r = new Random();
for(int i = 0 ; i < pass.length ; i++) {
int ch = 0;
ch = r.nextInt(3);
switch(ch) {
case 1:
if(passsettings.isIfDots()) {
String newchar = "";
newchar = dotpass();
pass[i] = newchar;
break;
}
case 2:
if(passsettings.isIfNum()) {
String newchar2 = "";
newchar2 = Numpass();
pass[i] = newchar2;
break;
}
case 3:
String newchar3 = "";
newchar3 = charchose();
pass[i] = newchar3;
break;
}
}
for(int i = 0 ; i < pass.length ; i++) {
String newpasschar = "";
newpasschar = pass[i];
password = password + newpasschar;
}
field.setText(password);
// random() end
}
public static String uppercasepass() {
Random r = new Random();
String passletter = "";
int rN3 = 0;
rN3 = r.nextInt(26);
switch(rN3) {
case 1:
passletter = "A";
case 2:
passletter = "B";
case 3:
passletter = "C";
case 4:
passletter = "D";
case 5:
passletter = "E";
case 6:
passletter = "F";
case 7:
passletter = "G";
case 8:
passletter = "H";
case 9:
passletter = "I";
case 10:
passletter = "J";
case 11:
passletter = "K";
case 12:
passletter = "L";
case 13:
passletter = "M";
case 14:
passletter = "N";
case 15:
passletter = "O";
case 16:
passletter = "P";
case 17:
passletter = "Q";
case 18:
passletter = "R";
case 19:
passletter = "S";
case 20:
passletter = "T";
case 21:
passletter = "U";
case 22:
passletter = "V";
case 23:
passletter = "W";
case 24:
passletter = "X";
case 25:
passletter = "Y";
case 26:
passletter = "Z";
}
return passletter;
// uppercase() end
}
public static String lowercasepass() {
Random r = new Random();
String passletter = "";
int rN3 = 0;
rN3 = r.nextInt(26);
switch(rN3) {
case 1:
passletter = "a";
case 2:
passletter = "b";
case 3:
passletter = "c";
case 4:
passletter = "d";
case 5:
passletter = "e";
case 6:
passletter = "f";
case 7:
passletter = "g";
case 8:
passletter = "h";
case 9:
passletter = "i";
case 10:
passletter = "j";
case 11:
passletter = "k";
case 12:
passletter = "l";
case 13:
passletter = "m";
case 14:
passletter = "n";
case 15:
passletter = "o";
case 16:
passletter = "p";
case 17:
passletter = "q";
case 18:
passletter = "r";
case 19:
passletter = "s";
case 20:
passletter = "t";
case 21:
passletter = "u";
case 22:
passletter = "v";
case 23:
passletter = "w";
case 24:
passletter = "x";
case 25:
passletter = "y";
case 26:
passletter = "z";
}
return passletter;
}
public static String Numpass() {
Random r = new Random();
String passletter = "";
int rN = 0;
rN = r.nextInt(9);
switch(rN) {
case 1:
passletter = "1";
case 2:
passletter = "2";
case 3:
passletter = "3";
case 4:
passletter = "4";
case 5:
passletter = "5";
case 6:
passletter = "6";
case 7:
passletter = "7";
case 8:
passletter = "8";
case 9:
passletter = "9";
}
return passletter;
}
public static String dotpass() {
Random r = new Random();
String passletter = "";
int rN5 = 0;
rN5 = r.nextInt(5);
switch(rN5) {
case 1:
passletter = "_";
case 2:
passletter = "]";
case 3:
passletter = "$";
case 4:
passletter = "#";
case 5:
passletter = "=";
}
return passletter;
}
public static String charchose() {
Random r = new Random();
String line = "";
int rN = 0;
rN = r.nextInt(20);
switch(rN) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
if(passsettings.isIfLowercase()) {
line = lowercasepass();
}
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
if(passsettings.isIfUpprcase()) {
line = uppercasepass();
}
}
return line;
}
}
The problem comes from the fact that Random.nextInt(n) return a value between 0-n (exclusive). Your switch case are all wrong by one.
This explain your null since you don't do anything for ch = 0, the String stays at null:
switch(ch){
case 1: ... //symbol
case 2 ... //number
case 3: ... //letter
}
This should be
switch(ch){
case 0: ... //symbol
case 1: ... //number
case 2: ... //letter
}
Some other issues or improvments :
You don't break after a case so you always get the last case executed (well all following case). Resulting in a possibilities of 4 character zZ9= (easy to bruteforce !)
You should use a char[] instead of String[], there is no need of using String to store one character like you do.
Instead of
String s = "a";
you can
char c = 'a';
Reducing the length of the code if you read the next point.
You can reduce your switch by doing some addition like 'a' + r.nextInt(26) to get a value between 'a' to 'z'
For a random symbol, instead of a switch, create a static array of char[] with every character, then get a random value using the size of this array.
Like :
final static char[] symbol = {'#', '#', '-', '\\', '/', '*'};
static getRadomSymbol(){
Random r = new Random();
return symbol[r.nextInt(symbol.length)];
}
Allowing the add of character easily (and reducing again the number of line ;) )
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 = "";
This question already has answers here:
If-else working, switch not [duplicate]
(9 answers)
In a switch statement, why are all the cases being executed?
(8 answers)
Closed 8 years ago.
For the following switch statement:
if a value between 0-9 is selected, output is fine. If value greater than 9 is selected, output is always a lowercase z.
for (int i = 0; i < 3; i++)
{
random[i] = randomnumber.nextInt(36);
if (random[i] > 9)
{
switch(random [i])
{
case 10: character[i] = "A";
case 11: character[i] = "B";
case 12: character[i] = "C";
case 13: character[i] = "D";
case 14: character[i] = "E";
case 15: character[i] = "F";
case 16: character[i] = "G";
case 17: character[i] = "H";
case 18: character[i] = "I";
case 19: character[i] = "J";
case 20: character[i] = "K";
case 21: character[i] = "L";
case 22: character[i] = "M";
case 23: character[i] = "N";
case 24: character[i] = "O";
case 25: character[i] = "P";
case 26: character[i] = "Q";
case 27: character[i] = "R";
case 28: character[i] = "S";
case 29: character[i] = "T";
case 30: character[i] = "U";
case 31: character[i] = "V";
case 32: character[i] = "W";
case 33: character[i] = "X";
case 34: character[i] = "Y";
case 35: character[i] = "Z";
}
}
else
character[i] = Integer.toString(random[i]);
A case statement is a form of standidised goto statement, it goes to the case statement and then continues on as usual. To get the behaviour you desire you need a
break;
at the end of each case
Where is the break of the cases man!
switch(random[i]){
case 10: ....
break;
case 11: ....
break;
//and so on
}
Add break with all case blocks like
case 10:
character[i] = "A";
break;
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);
}