I'm having issues with leading zeros - java

I'm attempting to get this to recognize the leading zeros in my program, and I thought using 'String.format("%03d", code);' would take care of it but I'm still not getting the expected result.
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String args[]){
Scanner sc =new Scanner(System.in);
System.out.println("Enter the shipment code :");
int code = sc.nextInt();
String.format("%03d", code);
// fill the code
if( code == 111 ){
System.out.println("All ways");
}
else if( code == 110){
System.out.println("Airway and Waterway");
}
else if( code == 011){
System.out.println("Waterway and Roadway");
}
else if( code == 010){
System.out.println("Waterway");
}
else if( code == 101){
System.out.println("Airway and Roadway");
}
else if(code == 001){
System.out.println("Roadway");
}
}
}

You're doing something wrong here.
011, 010, 001 are octal numbers, as they start with a zero.
Also, using String.format is pointless here, as the resulting value is not used.
This might be why your if branches aren't taken into consideration.
final String formattedValue = String.format("%03d", code);
Now you can use formattedValue as a comparison value for your if statements.
Example
if ("111".equals(formattedValue)) { ... }
Note that maybe transforming the int into a String isn't necessary. But in case you insist on doing so, a good practice is to use a constant String as the operand which calls equals(...).

You're discarding the formatted value. You need to store it in a variable and compare it as string:
String formatted = String.format("%03d", code);
if( formatted.equals("111") ){
System.out.println("All ways");
}
// ...

Well, String.format("%03d", code), returns a string, and you are comparing to integers (octal integers, as LppEdd pointed out).
You should store the formatted string to a variable, e.g.
String formatted = String.format("%03d", code);
and then compare it to Strings in your if/else statements, like so:
if(formatted.equals("011")) {...}

Don't format and remove any leading 0's in the condition and use switch
int code = sc.nextInt();
// fill the code
switch(code) {
case 111:
System.out.println("All ways");
break;
case 110:
System.out.println("Airway and Waterway");
break;
case 11:
System.out.println("Waterway and Roadway");
break;
case 10:
System.out.println("Waterway");
break;
case 101:
System.out.println("Airway and Roadway");
break;
case 1:
System.out.println("Roadway");
break;
default:
System.out.println("Unknown code " + code);
break;
}

Related

How do I use do/while with a case statement?

I want to generate a unique term that is one letter followed by two numbers, and then I want to check that it is not in a database. I have tried to use a do, followed by a while, but I cannot get it to work. I get an java: illegal start of expression error. Can you see what I am doing wrong? Alternatively, is there a better way to do this?
Here is my code:
public String setNumber(ReportType type) {
Random rand = new Random();
String number = String.format("%02d", rand.nextInt(100));
String prefix = "";
do {
switch (type) {
case CHILD:
prefix = "A";
break;
case ELDER:
prefix = "B";
break;
case BOOMER:
prefix = "C";
break;
}
String fullNumber = prefix + number;
while (dataBase.findInDataBase(fullNumber)) throws FileNotFoundException);
}
return fullNumber;
}
There are two syntax errors in your code:
The curly brace starting after do must end before while, not after it.
throws FileNotFoundException does not belong where it stands. You may have copied it from the declaration of the findInDataBase method or elsewhere. Just delete it.
Edit:
findInDataBase throws a FileNotFoundException exception when an
item is not found in the database. It does not return a boolean. When
nothing is found, I want to return the confirmed unique term. How do I
complete the while statement?
Use a try-catch construct to see if the exception is thrown. And a boolean variable to control the loop.
public String setNumber(ReportType type) {
Random rand = new Random();
String number = String.format("%02d", rand.nextInt(100));
String prefix = "";
String fullNumber;
boolean found;
do {
switch (type) {
case CHILD:
prefix = "A";
break;
case ELDER:
prefix = "B";
break;
case BOOMER:
prefix = "C";
break;
}
fullNumber = prefix + number;
try {
dataBase.findInDataBase(fullNumber);
found = true;
} catch (FileNotFoundException fnfe) {
found = false;
}
} while (found);
return fullNumber;
}
Alternative: The following might start an intense discussion since some find that it’s bad style. It simplifies a few things since it relieves us of having the two uninitialized variables declared before the loop.
public String setNumber(ReportType type) {
Random rand = new Random();
String number = String.format("%02d", rand.nextInt(100));
String prefix = "";
// This loop will be terminated by a return statement inside of it.
while (true) {
switch (type) {
case CHILD:
prefix = "A";
break;
case ELDER:
prefix = "B";
break;
case BOOMER:
prefix = "C";
break;
}
String fullNumber = prefix + number;
try {
dataBase.findInDataBase(fullNumber);
} catch (FileNotFoundException fnfe) {
// Nothing is found; return the confirmed unique term:
return fullNumber;
}
}
}
You are not out of problems yet. You will need to draw a new random number from rand every time through the loop. Otherwise if the first number drawn is already in the database, you are in an infinite loop. If all 100 numbers from 00 through 99 are in use, you will be anyway.
Note: Since Java SE 14*, you can use the switch expression instead of switch statement.
do {
prefix = switch (type) {
case CHILD -> "A";
case ELDER -> "B";
case BOOMER -> "C";
};
fullNumber = prefix + number;
} while (dataBase.findInDataBase(fullNumber));
* The switch expression was introduced with Java SE 12. However, it remained as a Preview feature in Java SE 12 and 13 and finally got standardized with Java SE 14. You can check this Q/A to learn more about it.

How do I keep looping in a do-while loop as long as the default part of a switch triggers?

What I am trying to accomplish: when the user types in anything other than 1 or 2, there will be a prompt saying "I don't understand you" and it would ask the user to choose 1 or 2 again without having to run the program each time.
Something like this:
do {
String a = input.nextLine();
num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
break;
case 2:
System.out.println("goodbye");
break;
default:
System.out.println("I don't understand you");
}
} while (num == default);
I know typing this will give me an error, so how do I compare it?
First, you have a potential infinite loop because the value for num which controls the stoping condition is never updated inside the loop.
Second, you could introduce a local variable to track when the user input was understood and exit the loop on that condition:
boolean understood;
do {
understood = false;
String a = input.nextLine();
int num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
understood = true;
break;
case 2:
System.out.println("goodbye");
understood = true;
break;
default:
System.out.println("i dont understand u");
break;
}
} while (!understood);
What you asked is technically a while(true) since everything which is not 1 or 2 is default. Also you should probably put your scanning bit in the loop.
If you try to check if value is different from 1 and 2 to ask again for a valid option:
do
{
// stuff
}
while( num != 1 && num != 2)
Since "default" is a keyword you just can not compare it to anything. It's meaningless though, because in your condition you used all possible cases(case 1 and case 2), so your code will never end, printing either "hello" or "goodbye" forever.

The operator || is undefined for the argument type

Java is really confusing me with its brackets and variables and I know with just a little help I can understand what the problem is and get on with it.
if(value1=||
Is where the error is.
Apologize in advance that indenting 8 spaces appears to have not had this pull in correctly either. help with that also appreciated...
import java.util.Scanner;
public class WTF {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("Please enter your Character");
String value1 =input.toString();
if (value1 ="a"||"A"||"e"||"E"||"i"||"I"||"o"||"O"||"u"||"U") {
System.out.print("You entered " +value1);
}
else System.out.print("Consonant");
}
}
You will have to check for every string seperately:
if (value1=="a"||value1=="A"||value1=="e"||value1=="E"||value1=="i"||value1=="I"||value1=="o"||value1=="O"||value1=="u"||value1=="U")
but this will most likely not work since == checks for identity on objects and not equality and String is an object. So you would have to write it like this:
if (value1.equals("a") || value1.equals("A") || value1.equals("e") || value1.equals("E") || value1.equals("i") || value1.equals("I") || value1.equals("o") || value1.equals("O") || value1.equals("u") || value1.equals("U")
This is just getting painfull so you could reduce this by setting value1 to upercase and just check for upercase values:
String value1_tmp = value1.toUperCase();
if (value1_tmp.equals("A") || value1_tmp.equals("E") || value1_tmp.equals("I") || value1_tmp.equals("O") || || value1_tmp.equals("U")
This is still kinda ugly so we can improve it by putting it in a method and using a switch statement
private static boolean isVowel(String s) {
switch(s.toUperCase()) {
case "A":
case "E":
case "I":
case "O":
case "U":
return true;
default:
return false;
}
}
and then use this method in your if check:
if (isVowel(value1)) { ...
Or if you are a fan of regular expressions simply do:
if (value1.matches("(?i)[aeiou]")) { ...
So many options, just choose one :)
EDIT: Also fix what Djehenghizz mentioned. Instead of
String value1 = input.toString();
do
String value1 = input.nextLine();
Also, change String value1=input.toString(); into String value1=input.nextLine(); because input is already string, you dont have to transform it.
|| Logical OR Operator only used to combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true.
here what you trying to do is using || between two character types. so It will raise an compile time error actually.
Right Way to check is ==>
Scanner reader = new Scanner(System.in);
char c = reader.nextChar(); //Correct way to Read Char from Console.
private boolean checkVowel(char c) {
switch(c) {
case 'A':
case 'a'
case 'E':
case 'e'
case 'I':
case 'i'
case 'O':
case 'o':
case 'u':
case 'U':
return true;
default:
return false;
}
}
Use below code
public static void main(String[] args) {
List<String> vowelsList = Arrays.asList("a","A","e","E","i","I","o","O","u","U" );
Scanner input =new Scanner(System.in);
System.out.println("Please enter your Character");
String value1 = input.next();
if (vowelsList.contains(value1)) {
System.out.print("You entered " +value1);
}
else System.out.print("Consonant");
}
Try
if (value1=="a"||value1=="A"||value1=="e"||value1=="E"||value1=="i"||value1=="I"||value1=="o"||value1=="O"||value1=="u"||value1=="U") //...
Or
if ("aeiouAEIOU".contains(value1))//...
String value1 =input.toString();
it means use get the info about the input -- a instance of Scanner Class ,the target of it is not what you input.
you may use
String value1 = input.next();
or
String value1 = input.nextLine();
Boolean operator is used to check the value of two boolean variables and returns a boolean value here you are using the operator to compare two strings which is not compatible.
as said earlier you used input.toString method to get the instance of the scanner class but it's not compatilbe instead of that you can use input.Read() or input.ReadLine().
For Strings you should use the .equals("Your Text here") method. should look like this:
if(value1.equals("a")||value1.equals("A")||value1.equals("e"))
and so on.

How can I check if my string is other than int's, to clarify i need to check it is not a number

... if instead of a number I get a letter, or a symbol, or 2 decimals.
I am making a change maker program in java.
Everything works good, the only thing i am confused about is checking the string to see if is invalid for my use,
I did this for when is left empty;
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "Invalid input! ");
System.exit(0);
}
That works perfect, now how can I do the else to check for letters or dots or symbols, anything that is not a number?
You could use regular expressions.
Here's some sample code to check for digits only (\\d) in your input string.
The code that actually checks is pattern.matcher(in).matches() and it tries to match the regular expression defined by regex
Let me know if you need more explanations
public class HelloWorld{
public static void main(String[] args) {
String regex = "\\d+";
String inputNumber = "2";
String inputDecimal = "2.0";
String inputString = "two";
String[] inputs = {inputDecimal, inputNumber, inputString };
Pattern pattern = Pattern.compile(regex);
for(String in: inputs){
System.out.print( in + " ");
System.out.print( pattern.matcher(in).matches()? "":"does not");
System.out.print( " contain integer numbers" );
System.out.println("---");
}
}
}
If you need to perform all the processing only when the String is integer why not check for integer value in the if clause and let the else clause be common for all the letter, dots, symbols and also empty.
if(s1.isNum){
//all processing here
}
else{
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Otherwise you could also use try and catch block.
try{
int num= Integer.parseInt(s1);
//rest of the processing
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Use either according to your requirement
You could use a regular expression1 and String.matches(String) which Tells whether or not this string matches the given regular expression. \\d+ should match one or more digits. Something like
System.out.println("12".matches("\\d+"));
Prints
true
1Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems. --jwz
To test whether it is an integer, parse it to an int like this:
Integer.parseInt(s1)
You might also want to make use of the value returned but I don't show it here. Now you can apply try catch blocks around the method call and catch NumberFormatException like this:
try {
Integer.parseInt(s1);
//The code here will run if s1 is an integer.
} catch (NumberFormatException e) {
//this will be executed when s1 is not an integer
}
You can also extract a method from the above code. A method that returns true when the exception is not thrown. However, a disadvantage of try catch is that throwing an exception needs time and thus, it slows down your program.
To test whether the string is a letter, you loop through all the chars in the string and use one of the methods of the Character class.
boolean isLetter = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isLetter(s1.charAt(i))) {
isLetter = false;
break;
}
}
If isLetter is true, it is a letter. Again, you can also extract this as a method.
To check whether it is a symbol, use one of the methods of the Character class (again).
boolean isSymb = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isJavaIdentifierStart(s1.charAt(i))) {
isSymb = false;
break;
}
}
To check for dots in a string, just use
s1.contains(".")
Isn't that simple?
Ok, I solved the problem the following way... I took a little bit of every idea lol...
if (s1 == null) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
for (int i = 0; i < s1.length(); i = i + 1) {
if (!Character.isDigit(s1.charAt(i))) {
JOptionPane.showMessageDialog(null, "You must enter an integer value");
System.exit(0);
}
}

Multiple characters in a switch statement?

just to clarify this is hw.
In a project we're doing, a user isn't allowed to enter numbers or special characters (i.e ! # £ etc)
char letter;
String phonetic;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter: ");
letter = letter = kb.next().charAt(0);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
case '1,2,3,4,5,6,7,8,9,0':
{
System.out.println('No number input please!');
}
break;
}
The error is on
'1,2,3,4,5,6,7,8,9,0'
Eclipse says
invalid character constant
Isn't it really long winded if I have to enter all the numbers manually?
i.e. case '1': case '2':
even with
case 1,2,3,4,5,6,7,8,9,0:
It won't work.
Is there an shorter way to do this using switch statements?
Thank you!
Its because Case expression should be an int-compatible literal or a String from java 7.
case '1,2,3,4,5,6,7,8,9,0':
character literals are represented using single quotes. c, it should only be of one length, while your case doesn't reflect that, thus the error.
'1,2,3,4,5,6,7,8,9,0' this is not a legal character.
If you just wanna check if the character is only alpha, then use Charcter#isDigit(char) or Charcter#isLetter before the switch starts like in below code:
char ch= (Character.toUpperCase(letter);
if(!Character.isDigit(ch)) {
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
}
}
else {
System.out.println("no numbers please")
}
There's no easier way using case, what about?:
if ('0' <= letter && letter <= '9')
System.out.println('No number input please!');
Isn't it really long winded if I have to enter all the numbers manually?
Yes.
Is there an shorter way to do this using switch statements?
No.
Consider an if statement instead...
No, Java in this situation is not smart like C#. You need to write multiple lines for that. If you want to compare strings you need to use if statements. Also remember to use this code for comparision:
if("search".equals(string2)) {...}
You cannot compare by == this would only compare the memory addresses. Also note that I use the equals on the static string and not on the variable string2 because you code would break if string2 is null.
I hope this one enlighten you more.
Consider, your expression generates output as A , B, C, D, E, F, G, H, I, ...till Z. and you want to execute same method/function for all them.
Then, you can check the ascii values of the characters and modify your code to use if and for loop or else use switch as mentioned in the program in following example program.
Play around with code to learn more.
public class SwitchClass
{
public void method1()
{
System.out.println("Menthod 1");
}
public void method2()
{
System.out.println("Menthod 2");
}
public void method3()
{
System.out.println("Menthod 3");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
SwitchClass sw = new SwitchClass();
System.out.println("Enter the String:");
String input = in.next();
for(int i = 0; i<input.length(); i++)
{
switch(Character.toUpperCase(input.charAt(i)))
{
case 'A':
case 'B':
case 'C':
case 'U':
System.out.println(Character.toUppercase(input.charAt(i))+" Case calling");
sw.method1();
sw.method2();
sw.method3();
break;
default:
System.out.println("No number input please!");
break;
}
}
}
}

Categories