Switch statement always selects same case [duplicate] - java

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;

Related

Time in Text - Java

I made a code that formats the typed time(numbers) into text. But the problem is when it's for example 10:30 he text should be "halb elf uhr" and not "halb zehn uhr" (language is german). So I think the case must be increased but how can I do this.
I tried it with case+1 but that diddn't work.
This is the code:
public class TimeAsText {
public static void main(String[] args) {
System.out.println("Type Hour: ");
int hours = In.readInt();
System.out.println("Type minutes: ");
int minutes = In.readInt();;
if(hours <1 || hours >12) {
System.out.println("*****");
System.exit(0);
}else if (minutes <0 || minutes >59) {
System.out.println("****");
System.exit(0);
}else {
String hourNames = null;
switch(hours) {
case 1: hourNames = "ein";break;
case 2: hourNames = "zwei";break;
case 3: hourNames = "drei";break;
case 4: hourNames = "vier";break;
case 5: hourNames = "fuenf";break;
case 6: hourNames = "sechs";break;
case 7: hourNames = "sieben";break;
case 8: hourNames = "acht";break;
case 9: hourNames = "neun";break;
case 10: hourNames = "zehn";break;
case 11: hourNames = "elf";break;
case 12: hourNames = "zwoelf";break;
default: System.out.println("Type valid hour");
}
String minuteNames = null;
switch(minutes) {
case 0: minuteNames = "punkt";break;
case 1: minuteNames = "eines";break;
case 2: minuteNames = "zwei";break;
case 3: minuteNames = "drei";break;
case 4: minuteNames = "vier";break;
case 5: minuteNames = "fuenf";break;
case 6: minuteNames = "sechs";break;
case 7: minuteNames = "sieben";break;
case 8: minuteNames = "acht";break;
case 9: minuteNames = "neun";break;
case 10: minuteNames = "zehn";break;
case 11: minuteNames = "elf";break;
case 12: minuteNames = "zwoelf";break;
case 13: minuteNames = "dreizehn";break;
case 14: minuteNames = "vierzehn";break;
case 15: minuteNames = "viertel nach";break;
case 16: minuteNames = "sechzehn";break;
case 17: minuteNames = "siebzehn";break;
case 18: minuteNames = "achtzeh";break;
case 19: minuteNames = "neunzehn";break;
case 20: minuteNames = "zwanzig";break;
case 21: minuteNames = "einundzwanzig";break;
case 22: minuteNames = "zweiundzwanzig";break;
case 23: minuteNames = "dreiundzwanzig";break;
case 24: minuteNames = "vierundzwanzig";break;
case 25: minuteNames = "fuenfundzwanzig";break;
case 26: minuteNames = "sechsundzwanzig";break;
case 27: minuteNames = "siebenundzwanzig";break;
case 28: minuteNames = "achtundzwanzig";break;
case 29: minuteNames = "neunundzwanzig";break;
case 30: minuteNames = "halb";break;
case 31: minuteNames = "einunddreißig";break;
case 32: minuteNames = "zweiunddreißig";break;
case 33: minuteNames = "dreiunddreißig";break;
case 34: minuteNames = "vierunddreißig";break;
case 35: minuteNames = "fuenfunddreißig";break;
case 36: minuteNames = "sechsunddreißig";break;
case 37: minuteNames = "siebenunddreißig";break;
case 38: minuteNames = "achtunddreißig";break;
case 39: minuteNames = "neununddreißig";break;
case 40: minuteNames = "vierzig";break;
case 41: minuteNames = "einundvierzig";break;
case 42: minuteNames = "zweiundvierzig";break;
case 43: minuteNames = "dreiundvierzig";break;
case 44: minuteNames = "vierundvierzig";break;
case 45: minuteNames = "dreiviertel";break;
case 46: minuteNames = "sechsudvierzig";break;
case 47: minuteNames = "siebenundvierzig";break;
case 48: minuteNames = "achtundvierzig";break;
case 49: minuteNames = "neunundvierzig";break;
case 50: minuteNames = "fuenfzig";break;
case 51: minuteNames = "einundfuenfzig";break;
case 52: minuteNames = "zwweiundfuenfzig";break;
case 53: minuteNames = "dreiundfuenfzig";break;
case 54: minuteNames = "vierundfuenfzig";break;
case 55: minuteNames = "fuenfundfuenfzig";break;
case 56: minuteNames = "sechsundfuenfzig";break;
case 57: minuteNames = "siebenundfuenfzig";break;
case 58: minuteNames = "achttundfuenfzig";break;
case 59: minuteNames = "neunundfuenfzig";break;
default: minuteNames = "Type valid nummer";break;
}
if(minutes == 0) {
System.out.println(minuteNames + " " + hourNames + " uhr");
}else if(minutes == 15) {
System.out.println(minuteNames + " " + hourNames + " uhr");
}else if(minutes == 30) {
System.out.println(minuteNames + " " + hourNames + " uhr");
}else if (minutes == 45) {
System.out.println(minuteNames + " " + hourNames + " uhr");
}else {
System.out.println(hourNames + " uhr " + minuteNames);
}
}
}
}
The problem is sometimes you want to use the name of hours+1.
It is easiest to tackle such problems using the abstraction of several methods.
public static void main(String[] args) {
System.out.println("Type Hour: ");
int hours = In.readInt();
System.out.println("Type minutes: ");
int minutes = In.readInt();;
if (hours < 1 || hours > 12) {
System.out.println("*****");
System.exit(0);
} else if (minutes < 0 || minutes > 59) {
System.out.println("****");
System.exit(0);
}
System.println("Zeit: " + zeit(hours, minutes));
}
static String zeit(int hours, int minutes) {
if (minutes == 0) {
return hourName(hours) + " Uhr");
} else if (minutes == 15) {
return "Viertel nach " + hourName(hour) + " Uhr"); // Quarter past
// Ex-DDR:
//return "Viertel " + hourName(1 + (hour % 12)) + " Uhr"):
} else if (minutes == 30) {
int nextHour = hours + 1;
if (nextHour > 12) {
nextHour = 1;
}
return "Halb " + hourName(nextHour) + " Uhr");
} else if (minutes == 45) {
int nextHour = hours + 1;
if (nextHour > 12) {
nextHour = 1;
}
return "Viertel vor " + hourName(nextHour) + " Uhr");
} else {
return hourName(hours) + " Uhr " + minuteName(minutes));
}
}
static String hourName(int hours) {
String hourNames = null;
switch(hours) {
case 1: hourNames = "ein";break;
case 2: hourNames = "zwei";break;
case 3: hourNames = "drei";break;
case 4: hourNames = "vier";break;
case 5: hourNames = "f\u00FCnf";break;
case 6: hourNames = "sechs";break;
case 7: hourNames = "sieben";break;
case 8: hourNames = "acht";break;
case 9: hourNames = "neun";break;
case 10: hourNames = "zehn";break;
case 11: hourNames = "elf";break;
case 12: hourNames = "zw\u00F6lf";break;
default: System.out.println("Type valid hour");
}
return hourNames;
}
static String minuteName(int minutes) {
String minuteNames = null;
switch(minutes) {
case 0: minuteNames = "punkt";break;
case 1: minuteNames = "eines";break;
case 2: minuteNames = "zwei";break;
case 3: minuteNames = "drei";break;
case 4: minuteNames = "vier";break;
case 5: minuteNames = "f\u00FCnf";break;
case 6: minuteNames = "sechs";break;
case 7: minuteNames = "sieben";break;
case 8: minuteNames = "acht";break;
case 9: minuteNames = "neun";break;
case 10: minuteNames = "zehn";break;
case 11: minuteNames = "elf";break;
case 12: minuteNames = "zw\u00F6lf";break;
case 13: minuteNames = "dreizehn";break;
case 14: minuteNames = "vierzehn";break;
case 15: minuteNames = "f\u00FCnfzehn";break;
case 16: minuteNames = "sechzehn";break;
case 17: minuteNames = "siebzehn";break;
case 18: minuteNames = "achtzeh";break;
case 19: minuteNames = "neunzehn";break;
case 20: minuteNames = "zwanzig";break;
case 21: minuteNames = "einundzwanzig";break;
case 22: minuteNames = "zweiundzwanzig";break;
case 23: minuteNames = "dreiundzwanzig";break;
case 24: minuteNames = "vierundzwanzig";break;
case 25: minuteNames = "f\u00FCnfundzwanzig";break;
case 26: minuteNames = "sechsundzwanzig";break;
case 27: minuteNames = "siebenundzwanzig";break;
case 28: minuteNames = "achtundzwanzig";break;
case 29: minuteNames = "neunundzwanzig";break;
case 30: minuteNames = "halb";break;
case 31: minuteNames = "einunddreißig";break;
case 32: minuteNames = "zweiunddreißig";break;
case 33: minuteNames = "dreiunddreißig";break;
case 34: minuteNames = "vierunddreißig";break;
case 35: minuteNames = "fuenfunddreißig";break;
case 36: minuteNames = "sechsunddreißig";break;
case 37: minuteNames = "siebenunddreißig";break;
case 38: minuteNames = "achtunddreißig";break;
case 39: minuteNames = "neununddreißig";break;
case 40: minuteNames = "vierzig";break;
case 41: minuteNames = "einundvierzig";break;
case 42: minuteNames = "zweiundvierzig";break;
case 43: minuteNames = "dreiundvierzig";break;
case 44: minuteNames = "vierundvierzig";break;
case 45: minuteNames = "dreiviertel";break;
case 46: minuteNames = "sechsudvierzig";break;
case 47: minuteNames = "siebenundvierzig";break;
case 48: minuteNames = "achtundvierzig";break;
case 49: minuteNames = "neunundvierzig";break;
case 50: minuteNames = "fuenfzig";break;
case 51: minuteNames = "einundfuenfzig";break;
case 52: minuteNames = "zwweiundfuenfzig";break;
case 53: minuteNames = "dreiundfuenfzig";break;
case 54: minuteNames = "vierundfuenfzig";break;
case 55: minuteNames = "fuenfundfuenfzig";break;
case 56: minuteNames = "sechsundfuenfzig";break;
case 57: minuteNames = "siebenundfuenfzig";break;
case 58: minuteNames = "achttundfuenfzig";break;
case 59: minuteNames = "neunundfuenfzig";break;
default: minuteNames = "Type valid nummer";break;
}
return minuteNames;
}
If you already know the modulo operator %:
int nextHour = 1 + (hours % 12);
Try this.
System.out.println("Type Hour: ");
int hours = In.readInt();
System.out.println("Type minutes: ");
int minutes = In.readInt();
if (minutes == 30)
{
hours++;
}
I think you have to do some Object Oriented programming. I would create an interface WordFormat with a method like
public String format(int hours, int minutes)
and a concrete class that hods your implementation.
then you can create other concrete class that translate in a different way following certain rules (if minutes are 30 then return else null).
at the end a class that allows you a logic like: given the ordered WordFormat, try to apply the first, if it fails (return null in my example) apply the second and so on until your last, default format...

Keep getting Null on String with Random

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

Java switch statement about number

I have a switch statement which works fine, but I feel like it's poorly formatted and redundant(many of the cases do the same thing). How can I improve this?
switch (number) {
case 10: // do 1
break;
case 12: // do 2
break;
case 13: // do 1
break;
case 15: // do 3
break;
case 17: // do 2
break;
case 18: // do 2
break;
}
I guess you can group the cases with the same output together. It is one way to improve this.
switch (number) {
case 10:
case 13:
// do 1
break;
case 12:
case 17:
case 18:
// do 2
break;
case 15:
// do 3
break;
}
break; is used to terminate a case in the switch statement. So, the cases will have same output when there is no break; between them.
You could improve it by removing a few break statement, like this
switch (number) {
case 10:
case 13: // do 1
break;
case 12:
case 17:
case 18: // do 2
break;
case 15: // do 3
break;
}
You may make it a bit more compact like this:
switch (number) {
case 10:
case 13:
System.out.println("do 1 + " + number);
break;
case 12:
case 17:
case 18:
System.out.println("do 2 + " + number);
break;
case 15:
System.out.println("do 3 + " + number);
break;
}
And the last break; is not required in your case but good practice anyways for defensive programming.
You can add default case. When provided cases are not equal to number default statement is executed. Code:
int number = 0;
switch (number) {
case 10: // do 1
break;
case 12: // do 2
break;
case 13: // do 1
break;
case 15: // do 3
break;
case 17: // do 2
break;
case 18: // do 2
break;
default:
System.out.println(number);
}

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;

Input Repeat with same case

After I run this codes, it says BUILD SUCCESSFUL and it stops. What should I do to make it repeat to ask another input with same case? I did read tutorial on several web but I'm not helped by those.
Here's the code:
import java.util.Scanner;
public class SwitchTry {
public static void main(String[] args) {
int mth;
String mthString;
Scanner scanner = new Scanner(System.in);
mth =scanner.nextInt();
switch (mth) {
case 1: mthString = "January";
break;
case 2: mthString = "February";
break;
case 3: mthString = "March";
break;
case 4: mthString = "April";
break;
case 5: mthString = "May";
break;
case 6: mthString = "June";
break;
case 7: mthString = "July";
break;
case 8: mthString = "August";
break;
case 9: mthString = "September";
break;
case 10: mthString = "October";
break;
case 11: mthString = "November";
break;
case 12: mthString = "December";
break;
default: mthString = "Error";
break;
}
System.out.println(mthString);
}
}
I appreciate any help that you can provide.
I would try using a while loop to encase the switch. So it keeps asking your input.
import java.util.Scanner;
public class SwitchTry {
public static void main(String[] args) {
while(true){
int mth;
String mthString;
Scanner scanner = new Scanner(System.in);
mth =scanner.nextInt();
switch (mth) {
case 1: mthString = "January";
break;
case 2: mthString = "February";
break;
case 3: mthString = "March";
break;
case 4: mthString = "April";
break;
case 5: mthString = "May";
break;
case 6: mthString = "June";
break;
case 7: mthString = "July";
break;
case 8: mthString = "August";
break;
case 9: mthString = "September";
break;
case 10: mthString = "October";
break;
case 11: mthString = "November";
break;
case 12: mthString = "December";
break;
default: mthString = "Error";
break;
}
System.out.println(mthString);
}
}
}
As suggested by MadProgarmmer do-while loop is the perfect use-case for such scenarios. You need to wrap your input line plus switch cases and print statement inside the do-while loop as follow:
do {
//so you know that terminal is asking for input
System.out.println("Input: ");
mth =scanner.nextInt();
//copy/paste your switch case with last System.out.println() here
} while (true);
I am worried about having execution that never ends. Maybe you want to end the loop when the user supplies -1, so change the while(true) to while (mth != -1) and that should be your termination input.

Categories

Resources