Java switch statement not working, even 'default' isn't - java

My switch statement isn't working as whole.
I have never used switch in Java, and I dont know what I did wrong. It is also not executing default. I looked some info up about switch statements, and I think maybe it is because of this line:
if (pair.length == 2) {
// Voorbeeld van het gebruik van de key/value pairs
switch (pair[0]) {
because what I looked up it looked like everybody was using a variable on the pair[0] spot.
Thanks in advance!
String scanString = result.getText(); // result.getText();
String[] parts = scanString.split("\\||");
// Loop alle delen tussen | langs
for (String part : parts) {
String[] pair = part.split("\\|"); // Bevat de key en value pair voor en na het streepje
if (pair.length == 2) {
// Voorbeeld van het gebruik van de key/value pairs
switch (pair[0]) {
case "po":
System.out.println("Productieorder: " + pair[1]);
edt2.setText(pair[1]);
break;
case "tnr":
System.out.println("Tekeningnummer: " + pair[1]);
break;
case "ref":
System.out.println("Referentie: " + pair[1]);
break;
case "hafa":
System.out.println("Half Fabrikaat: " + pair[1]);
break;
case "art":
System.out.println("Artikel: " + pair[1]);
break;
case "atl":
System.out.println("Aantal: " + pair[1]);
break;
case "loc":
System.out.println("Locatie: " + pair[1]);
edt4.setText(pair[1]);
break;
default:
System.out.println("NIET GELUKT");
}
}
}
Edit
I Will try simply this: if (pair.length > 2) instead of == 2, I acually don't even know why it was == 2, because I need to scan qr string that can exist out of more than 3000 chars.

Problem is here.
String[] parts = scanString.split("\\||");
It is no difference from
String[] parts = scanString.split("");
It will split every letters of the string.
For example:
"Hello".split("\\||")
Its return value is an array like
["H","e","l","l","o"]
If you want to split a string by two | , you should write:
String[] parts = scanString.split("\\|\\|")

Problem is in String[] parts = scanString.split("\||");
and String[] pair = part.split("\|"); which spliting string by character.
and the condition if (pair.length == 2) is checking size 2 whic returns false so the control isn't entering into the switch block.
You can install a breakpoint and debug it.

You should use split("\\|") if wanting to split by |; split("\\|\\|") if wanting to split by ||.
Otherwise the second | without regex escape \ will be an OR, and as such the string is split on the empty string too, giving an array of strings containing just one letter (though not |).

If you are using split function and then you need to keep in mind below points. This function does not take as it is input to split.
one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\"
two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter

Related

How do separate out these elements of an equation in a string to a required format?

I have a string input which looks like this:
String equation = "(5.5 + 65) - 33".
How would I go about separating these elements into an array which looked like this:
String array = {"(", "5.5", "+", "65", ")", "-", "33"}
I tried using the string split() method but because of there being no spaces between the parenthesis and the next digit it produces the incorrect format of:
String array = {"(5.5", "+"
You can do this with a StreamTokenizer:
StreamTokenizer st = new StreamTokenizer(new StringReader(equation));
st.parseNumbers();
List<String> tokens = new ArrayList<>();
while (st.nextToken() != StreamTokenizer.TT_EOF) {
switch (st.ttype) {
case StreamTokenizer.TT_EOL:
// ignore
break;
case StreamTokenizer.TT_WORD:
tokens.add(st.sval);
break;
case StreamTokenizer.TT_NUMBER:
tokens.add(String.valueOf(st.nval));
break;
default:
tokens.add(String.valueOf((char) st.ttype));
}
}
String[] array = tokens.toArray(new String[tokens.size()]);
Note that because this parses the numbers as double, they become e.g. 65.0 when converted back to strings. If you don't want that, you'll need to add some number formatting.
I suspect that whatever you're planning to do with them later, you actually want them as numbers though.

How can I test if a character is a vowel using a single if statement? [duplicate]

This question already has answers here:
can you have two conditions in an if statement
(6 answers)
Closed 2 years ago.
How can I test if a single character is a vowel, using a single if statement?
More practically, how can I consolidate my current logic below into a single if statement?
if (valor == 'a'); System.out.println("xdd");
if (valor == 'e'); System.out.println("xdd");
if (valor == 'i'); System.out.println("xdd");
if (valor == 'o'); System.out.println("xdd");
if (valor == 'u'); System.out.println("xdd");
Try this. This will work whether valor is a character or a string.
if ("aeiou".indexOf(valor) >= 0) {
System.out.println("xdd");
}
You can try String.indexOf()
final String vowels = "aeiou";
char valor = 'e';
if (vowels.indexOf(valor) != -1) {
System.out.println("xdd");
}
You can leverage the || operator which basically serves as a or in a statement like so:
if(valor=='a'||valor=='e'||valor=='i'||valor=='o'||valor=='u'){
System.out.println("xdd");
}
Since in this case, it will always print the same thing.
One easy method, which can also be easily expanded, is using an index string and checking if your variable is part of that String.
String vowels = "aeiou";
if (vowels.indexOf(valor) >= 0) {
// do whatever you have to
}
Let valor is a character converted to String, then:
if ("AaEeIiOoUu".contains(valor)) {
System.out.println("xdd");
}
Use a regex.
String str = "a";
if (str.matches("[AaeEiIoOuU]") {
System.out.println("It's a vowel!");
}
else {
System.out.println("it's not a vowel!");
}
You can easily achieve this by using the if conditional statements with java logical OR operator.
Using short circuit OR operator
This will be more efficient because this will return true at the first point when java meets the satisfying condition while checking the logical condition.
if(valor=='a'||valor=='e'||valor=='i'||valor=='o'||valor=='u'){
System.out.println("xdd");
}
As many suggested, you can use indexOf or ||. I'll not repeat myself. You can use something as follows as well,
public class VowelOrNot {
public static void main(String[] args) {
String valor = "z";
switch (valor.toLowerCase()) {
case "a":
case "e":
case "i":
case "o":
case "u":
System.out.println(valor + " is vowel");
break;
default:
System.out.println(valor + " is consonant");
}
}
}
I'm using switch case. Which is handy when you want to avoid if-else/if-if ladder in multiple scenarios. Basically, if the input is matched with any of the case then it prints that string is a vowel else it is a consonant. Note, that break is important. Otherwise it will check default case and print consonant if given valor is a vowel.
If you want, you replace String with char in the variable declaration and handle it appropriately in switch cases.

match exact the same words between 2 strings

I would like to compare and match exactly one word (characters and length) between two strings.
This is what I have:
String wordCompare = "eagle:1,3:7;6\nBasils,45673:ewwsk\nlola:flower:1:2:b";
String lolo = scanner.nextLine();
if ( motCompare.toLowerCase().indexOf(lolo.toLowerCase()) != -1 ) {
System.out.println("Bingo !!!");
} else {
System.out.println("not found !!!");
}
If I type eagle:1,3:7;6 it should display Bingo !!!
If I type eagle:1,3 it still displays Bingo !!! which is wrong, it should display Not found.
If I type eagle:1,3:7;6 Basils,45673:ewwsk or eagle:1,3:7;6\nBasils,45673:ewwsk it should also display Not Found. Length of the typed word should be acknowledged between \n.
If I type Basils,45673:ewwsk, it displays bingo !!!
It looks like what you're wanting is an exact match, with the words being split by the newline character. With that assumption in mind, I would recommend splitting the string out into an array and then loading that into a HashSet like so:
boolean search(String wordDictionary, String search){
String[] options = wordDictionary.split("\n");
HashSet<String> searchSet = new HashSet<String>(Arrays.asList(options));
return searchSet.contains(search);
}
If the search function returns true, it has found whatever word you're searching for, if not, it hasn't.
Installing it in your code will look something like this:
String wordCompare = "eagle:1,3:7;6\nBasils,45673:ewwsk\nlola:flower:1:2:b";
String lolo = scanner.nextLine();
if(search(wordCompare, lolo))
System.out.println("Bingo!!!");
else
System.out.println("Not found.");
(For the record, you'd probably be better off with more clear variable names)
As #Grey has already mentioned within his answer, since you have a newline tag (\n) between your phrases you can Split the String using the String.split() method into a String Array and then compare the elements of that Array for equality with what the User supplies.
The code below is just another example of how this can be done. It also allows for the option to Ignore Letter case:
boolean ignoreCase = false;
String userString = "Basils,45673:ewwsk";
String isInString = "'" + userString + "' Was Not Found !!!";
String wordCompare = "eagle:1,3:7;6\nBasils,45673:ewwsk\nlola:flower:1:2:b";
String[] tmp = wordCompare.split("\n");
for (int i = 0; i < tmp.length; i++) {
// Ternary used for whether or not to ignore letter case.
if (!ignoreCase ? tmp[i].trim().equals(userString) :
tmp[i].trim().equalsIgnoreCase(userString)) {
isInString = "Bingo !!!";
break;
}
}
System.out.println(isInString);
Thank you,
The thing is I am not allowed to use regular expression nor tables.
so basing on your suggestions I made this code :
motCompare.toLowerCase().indexOf(lolo.toLowerCase(), ' ' ) != -1 ||
motCompare.toLowerCase().lastIndexOf(lolo.toLowerCase(),' ' ) != -1)
as a condition for a do while loop.
Could you please confirm if it is correct ?
Thank you.

StreamTokenizer mangles integers and loose periods

I've appropriated and modified the below code which does a pretty good job of tokenizing Java code using Java's StreamTokenizer. Its number handling is problematic, though:
it turns all integers into doubles. I can get past that by testing num % 1 == 0, but this feels like a hack
More critically, a . following whitespace is treated as a number. "Class .method()" is legal Java syntax, but the resulting tokens are [Word "Class"], [Whitespace " "], [Number 0.0], [Word "method"], [Symbol "("], and [Symbol ")"]
I'd be happy turning off StreamTokenizer's number parsing entirely and parsing the numbers myself from word tokens, but commenting st.parseNumbers() seems to have no effect.
public class JavaTokenizer {
private String code;
private List<Token> tokens;
public JavaTokenizer(String c) {
code = c;
tokens = new ArrayList<>();
}
public void tokenize() {
try {
// Create the tokenizer
StringReader sr = new StringReader(code);
StreamTokenizer st = new StreamTokenizer(sr);
// Java-style tokenizing rules
st.parseNumbers();
st.wordChars('_', '_');
st.eolIsSignificant(false);
// Don't want whitespace tokens
//st.ordinaryChars(0, ' ');
// Strip out comments
st.slashSlashComments(true);
st.slashStarComments(true);
// Parse the file
int token;
do {
token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_NUMBER:
// A number was found; the value is in nval
double num = st.nval;
if(num % 1 == 0)
tokens.add(new IntegerToken((int)num);
else
tokens.add(new FPNumberToken(num));
break;
case StreamTokenizer.TT_WORD:
// A word was found; the value is in sval
String word = st.sval;
tokens.add(new WordToken(word));
break;
case '"':
// A double-quoted string was found; sval contains the contents
String dquoteVal = st.sval;
tokens.add(new DoubleQuotedStringToken(dquoteVal));
break;
case '\'':
// A single-quoted string was found; sval contains the contents
String squoteVal = st.sval;
tokens.add(new SingleQuotedStringToken(squoteVal));
break;
case StreamTokenizer.TT_EOL:
// End of line character found
tokens.add(new EOLToken());
break;
case StreamTokenizer.TT_EOF:
// End of file has been reached
tokens. add(new EOFToken());
break;
default:
// A regular character was found; the value is the token itself
char ch = (char) st.ttype;
if(Character.isWhitespace(ch))
tokens.add(new WhitespaceToken(ch));
else
tokens.add(new SymbolToken(ch));
break;
}
} while (token != StreamTokenizer.TT_EOF);
sr.close();
} catch (IOException e) {
}
}
public List<Token> getTokens() {
return tokens;
}
}
parseNumbers() in "on" by default. Use resetSyntax() to turn off number parsing and all other predefined character types, then enable what you need.
That said, manual number parsing might get tricky with accounting for dots and exponents... With a scanner and regular expressions it should be relatively straightforward to implement your own tokenizer, tailored exactly to your needs. For an example, you may want to take a look at the Tokenizer inner class here: https://github.com/stefanhaustein/expressionparser/blob/master/core/src/main/java/org/kobjects/expressionparser/ExpressionParser.java (about 120 LOC at the end)
I'll look into parboiled when I have a chance. In the meantime, the disgusting workaround I implemented to get it working is:
private static final String DANGLING_PERIOD_TOKEN = "___DANGLING_PERIOD_TOKEN___";
Then in tokenize()
//a period following whitespace, not followed by a digit is a "dangling period"
code = code.replaceAll("(?<=\\s)\\.(?![0-9])", " "+DANGLING_PERIOD_TOKEN+" ");
And in the tokenization loop
case StreamTokenizer.TT_WORD:
// A word was found; the value is in sval
String word = st.sval;
if(word.equals(DANGLING_PERIOD_TOKEN))
tokens.add(new SymbolToken('.'));
else
tokens.add(new WordToken(word));
break;
This solution is specific to my needs of not caring what the original whitespace was (as it adds some around the inserted "token")

StreamTokenizer doesn't treat + as word

In code
switch(token){
case StreamTokenizer.TT_EOF:
eof = true;
break;
case StreamTokenizer.TT_NUMBER:
double value = tokenizer.nval;
operands.add(value);
break;
case StreamTokenizer.TT_WORD:
operate(tokenizer.sval);
break;
default:
throw new WrongPhraseException("Unnexpected operator or operand: " + tokenizer.sval +".");
}
I give as input RPN, ex: 5 4 3 + *
Why is + not treated as TT_WORD, it isn't treated as it so it throws Exception.
From the StreamTokenizer documentation:
For a single character token, its value is the single character, converted to an integer.
Since your + character is single character, it is probably being treated as TT_NUMBER; your case statement for TT_NUMBER will need to handle these cases as well. The same will apply for your unquoted * character as well, I assume. Thus you might try something like this:
case StreamTokenizer.TT_NUMBER:
Double value = new Double(tokenizer.nval);
if (Character.isDigit(value.intValue()) {
operands.add(value.doubleValue());
} else {
// Possibly dealing with operator here. The hard/fun part is
// in coercing that double value back to its tokenized string
// form.
operate(new Character((char) tokenizer.nval).toString());
}
break;
Hope this helps!

Categories