sorting by first character - java

The question at hand is each policy No. is a string of 9 characters of which indicates the type of insurance policy
B for building policy
C for Contents Policy
L for Life policy
V for car policy
Each of the remaining 8 characters of the policy number is a decimal digit.
I have tried using charAt but somebody told me there was a slightly better way
public String getpolicyNo(String initpolicyNo) {
/**
* Access method to find the first character of the policy to then
* determine what type of policy it is.
*/
String b = "B";
String C = "C";
String L = "L";
String V = "V";
char c1 = b.charAt(0);
char c2 = C.charAt(0);
char c3 = L.charAt(0);
char c4 = V.charAt(0);
if (c1 == 0) {
System.out.println("Its building" + c1);
return initpolicyNo;
} else {
if (c2 == 0) {
System.out.println("Its Content");
return initpolicyNo;
} else {
if (c3 == 0) {
System.out.println("Its life");
return initpolicyNo;
} else {
if (c4 == 0) {
System.out.println("Its car");
return initpolicyNo;
}
}
}
}
throw new IllegalArgumentException();
}
I'm not looking for you to provide an answer for me, I'm just looking for any possible alternatives and possible suggestions.
Many thanks
Dan

I'm not really sure what you are trying to achieve, but I would write this way:
public String getpolicyNo(String initpolicyNo) {
switch(initPolicyNo.charAt(0))
{
case 'B':
System.out.println("Its building B");
return initpolicyNo;
case 'C':
System.out.println("Its building C");
return initpolicyNo;
case 'L':
System.out.println("Its building L");
return initpolicyNo;
case 'V':
System.out.println("Its building V");
return initpolicyNo;
}
throw new IllegalArgumentException();
}

I recommend you using an Enum. Each value for an Enum has an ordinal value, which you can sort by.
If you want to read an introduction to Enums, the following site will help: Enum Types - The Java Tutorials
enum Policy {
BUILDING_POLICY, CONTENTS_POLICY, LIFE_POLICY, CAR_POLICY
}
For each enum value, you can assign a custom value, with which you can sort.

public void whatItIs(String s){
if(s.length() < 1){
//-- nothing to see here ---
return;
}
//-- case insensitive --
char c = Character.toUpperCase(s.charAt(0));
switch(c){
case 'B':
//-- its a building !--
break;
case 'C':
//-- its a c........ !--
break;
case 'L':
//-- its a l........ !--
break;
case 'V':
//-- its a v........ !--
break;
default:
//-- its something else :(--
}
}

public String getpolicyNo(String initpolicyNo) {
switch (initpolicyNo.charAt(0)) {
case 'B':
System.out.println("Its building" );
break;
case 'C':
System.out.println("Its Content");
break;
case 'L':
System.out.println("Its life");
break;
case 'V':
System.out.println("Its car");
break;
default:
throw new IllegalArgumentException();
break;
}
return initpolicyNo;
}

You could add enums to your code, or you could use a switch statement instead of the if/else block you currently have:
char type = initpolicyNo.charAt(0);
switch (type) {
case 'B':
// do stuff
break;
case 'C':
// do stuff
break;
}
Note: I think you may have a problem in your code in that it seems to me you should be switching on the initpolicyNo, not the actual types?

I have tried using charAt but somebody told me there was a slightly
better way
there is no better way to get the first letter of a string than using charAt.
And rather than having lots of if's/switches and what not, get a bit more OOPs up side your head.
Map<Character, String> myMap = new HashMap<Character, String>() {{
put('B', "Its building");
put('C', "Its content");
put('L', "its life");
put('V', "its vehicle");
}} ;
public void iShouldBeDoingMyOwnWork(String initpolicyNo) {
System.out.println(myMap.get(initpolicyNo.charAt(0)));
}

Related

How to comment string starting with "//" this?

I am learning compiler construction these days, and I am having trouble while making the code for comment in it.
What is actually happening is that when ever I am writing a string in the notepad file such as Hello //World. Then it is printing "/" this div operator which I don't want. What actually I want is that Hello should be printed in the output and World should get commented. I know I have included the code for div operator but it is also necessary to include. Just wanted to know how I can achieve this comment logic while checking the logic for checking the div operator should also be there.
Here is the code!
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class main {
public static void main(String[] args) throws FileNotFoundException{
File newFile = new File("C:/temp/sourcecode.txt");
Scanner scanFile = new Scanner(newFile);
//Scanner scan = new Scanner(System.in);
char ch;
String str;
while(scanFile.hasNextLine()){
str = scanFile.nextLine();
int l = str.length();
if(!str.startsWith("//") && !str.startsWith("/*") && !str.endsWith("*/")) {
for(int i =0; i<l ; i++) {
ch = str.charAt(i);
System.out.println(ch);
if(ch == '*'){
System.out.println("The Operator is MUL");
System.out.println("arop\n");
}
if(ch == '/')
{
System.out.println("The Operator is DIV");
System.out.println("arop\n");
}
}
}
int OP = 0;
switch(OP){
case 0:
if(str.contains("<") && str.contains(">")){
System.out.println("The Operator is NE");
System.out.println("relop\n");
break;
}
case 1:
if(str.contains("<") && str.contains("=")){
System.out.println("The Operator is LE");
System.out.println("relop\n");
break;
}
case 2:
if(str.contains(">") && str.contains("=")){
System.out.println("The Operator is GE");
System.out.println("relop\n");
break;
}
case 3:
if(str.contains("<")){
System.out.println("The Operator is LT");
System.out.println("relop\n");
break;
}
case 4:
if(str.contains(">")){
System.out.println("The Operator is GT");
System.out.println("relop\n");
break;
}
case 5:
if(str.contains("==")){
System.out.println("The Operator is EQ");
System.out.println("relop\n");
break;
}
case 6:
if(str.contains("+")){
System.out.println("The Operator is ADD");
System.out.println("arop\n");
break;
}
case 7:
if(str.contains("-")){
System.out.println("The Operator is SUB");
System.out.println("arop\n");
break;
}
// case 8:
// if(str.contains("*")){
// System.out.println("The Operator is MUL");
// System.out.println("arop\n");
// break;
// }
// case 9:
// if(str.contains("/")){
// System.out.println("The Operator is DIV");
// System.out.println("arop\n");
// break;
// }
case 10:
if(str.contains("=")){
System.out.println("The Operator is ASN");
System.out.println("otop\n");
break;
}
case 11:
if(str.contains("'")){
System.out.println("The Operator is PRN");
System.out.println("otop\n");
break;
}
case 12:
if(str.contains(";")){
System.out.println("The Operator is LTRN");
System.out.println("otop\n");
break;
}
case 13:
if(str.contains("{")){
System.out.println("The Operator is LBRC");
System.out.println("otop\n");
break;
}
case 14:
if(str.contains("}")){
System.out.println("The Operator is RBRC");
System.out.println("otop\n");
break;
}
}
}
}
}
Thank you in advance!
When programming a compiler the different input words in your code are called tokens, and the phase of recognising the role of each token is called the lexical analysis phase.
When trying to recognise tokens usually what is used is regex which is a way of implementing a finite automata.
You can read about it in much more detail here:
https://en.wikipedia.org/wiki/Lexical_analysis
You should replace the usage of contains, and use a lexer, it's the name of the tool that does lexical analysis. It uses regexes because it's not just about / and //, there can be many different situations where your compiler will need to decide which token to choose.
Here's an example of a finite automate for recognising different tokens, notice that for each prefix there can be many options for possible tokens:
In Java you can use jflex which will generate lexer code with your tokens definitions.
When you find a /, you need to check the next character.
if (ch == '/') {
char nextCh = (i + 1 < l ? str.charAt(i + 1) : '\0');
if (nextCh == '/') {
System.out.println("The Operator is EndOfLineComment");
System.out.println("arop\n");
i++;
} else if (nextCh == '*') {
System.out.println("The Operator is TraditionalComment");
System.out.println("arop\n");
i++;
} else {
System.out.println("The Operator is DIV");
System.out.println("arop\n");
}
}

Missing Return Statement in Nested Switch Statements

I'm writing a section of code for a Rock, Paper, Scissors game. I am writing a method that returns 1, 0 or -1 depending on wether the computer wins, it's a tie, or the user wins, respectively. I have this code so far:
private int nextPlay(char computerMove, char playerMove) {
switch (playerMove) {
case 'R': switch (computerMove) {
case 'R': return 0;
case 'P': return 1;
case 'S': return -1;
}
case 'P': switch (computerMove) {
case 'R': return -1;
case 'P': return 0;
case 'S': return 1;
}
case 'S': switch (computerMove) {
case 'R': return 1;
case 'P': return -1;
case 'S': return 0;
}
}
}
It throws a "Missing Return Statement" at me at the last bracket. Any suggestions?
P.S. the only options available for both computerMove and playerMove are R, P and S!
Others are telling you to add default to your switch statements. Not needed at all in this case, though it's a good general rule to follow.
However, you need to consider what should happen if playerMove and/or computerMove doesn't have one of the 3 expected values ('R', 'P', or 'S').
If computerMove doesn't, you'd want the logic flow to exit the outer switch statement, rather than fall through to the next case (though technically they'd all just fall through then, but still), so add a break in each outer case.
If that breaks out, or if playerMove doesn't have valid value, then logic flow gets to end of method, and there is no return statement there. That is your compilation error.
Best solution here, since you hopefully can't get into that situation, is to declare that to be exceptional, i.e. throw an Exception.
You code could be:
private int nextPlay(char computerMove, char playerMove) {
switch (playerMove) {
case 'R':
switch (computerMove) {
case 'R': return 0;
case 'P': return 1;
case 'S': return -1;
}
break;
case 'P':
switch (computerMove) {
case 'R': return -1;
case 'P': return 0;
case 'S': return 1;
}
break;
case 'S':
switch (computerMove) {
case 'R': return 1;
case 'P': return -1;
case 'S': return 0;
}
break;
}
throw new IllegalStateException("Oops! I messed up!!");
}
But it's better with more descriptive error messages:
private int nextPlay(char computerMove, char playerMove) {
switch (playerMove) {
case 'R':
switch (computerMove) {
case 'R': return 0;
case 'P': return 1;
case 'S': return -1;
}
throw new IllegalArgumentException("Invalid computer move: " + computerMove);
case 'P':
switch (computerMove) {
case 'R': return -1;
case 'P': return 0;
case 'S': return 1;
}
throw new IllegalArgumentException("Invalid computer move: " + computerMove);
case 'S':
switch (computerMove) {
case 'R': return 1;
case 'P': return -1;
case 'S': return 0;
}
throw new IllegalArgumentException("Invalid computer move: " + computerMove);
}
throw new IllegalArgumentException("Invalid player move: " + playerMove);
}
Now, you could add those throw statements in a default clause instead. Same result.
private int nextPlay(char computerMove, char playerMove) {
switch (playerMove) {
case 'R':
switch (computerMove) {
case 'R': return 0;
case 'P': return 1;
case 'S': return -1;
default: throw new IllegalArgumentException("Invalid computer move: " + computerMove);
}
case 'P':
switch (computerMove) {
case 'R': return -1;
case 'P': return 0;
case 'S': return 1;
default: throw new IllegalArgumentException("Invalid computer move: " + computerMove);
}
case 'S':
switch (computerMove) {
case 'R': return 1;
case 'P': return -1;
case 'S': return 0;
default: throw new IllegalArgumentException("Invalid computer move: " + computerMove);
}
default: throw new IllegalArgumentException("Invalid player move: " + playerMove);
}
}
my suggestion
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int x=nextPlay('R','P');
System.out.println(x);
}
private static int nextPlay(char computerMove, char playerMove)
{
if(playerMove=='R')
{
if(computerMove=='R')
return 0;
else if(computerMove=='P')
return 1;
else
return -1;
}
else if(playerMove=='P')
{
if(computerMove=='R')
return -1;
else if(computerMove=='P')
return 0;
else
return 1;
}
else
{
if(computerMove=='R')
return 1;
else if(computerMove=='P')
return -1;
else
return 0;
}
}
Thanks so much everyone! I decided to simply set one of the cases in each switch statement to default (keeping track of which char it is of course) and it resolved the issue.
I know this can cause some issues if the char is anything but the intended one, but my teacher says it is ok and I would use a different method (as suggested) next time!

Evaluator Expression: How to know if the input is wrong

I'm solving the next technical question (Q1): http://blog.sdeskills.com/qotd-2016-oct-17-resistance-is-futile/
It's almost done, just one task is pending. Evaluate if the input is balanced or not. Checking if parenthesis are in order, that's done, but not to evaluate the tokens.
In a given sub-network cannot have a mix of series / parallel
connections, so (500+200|300) is not allowed.
This is my current code: https://repl.it/EC3i/2 Any idea about how to evaluate the previous expression as wrong?
Try this. This code checks operator sereis and also balanced parentheses.
static boolean isBalanced(String s) {
Deque<Character> operators = new LinkedList<>();
operators.push('#');
for (int i = 0; i < s.length(); ++i) {
if (operators.isEmpty()) return false;
char ch = s.charAt(i);
switch (ch) {
case '(': operators.push('#'); break;
case ')': operators.pop(); break;
case '+':
switch (operators.peek()) {
case '#': operators.pop(); operators.push(ch); break;
case '+': break;
default: return false;
}
break;
case '|':
switch (operators.peek()) {
case '#': operators.pop(); operators.push(ch); break;
case '|': break;
default: return false;
}
break;
}
}
return operators.size() == 1;
}
And JUnit test codes.
#Test
public void testIsBalanced() {
assertTrue(isBalanced("(2)"));
assertTrue(isBalanced("(2+3+3)"));
assertTrue(isBalanced("2+3+3"));
assertTrue(isBalanced("2+(4|5|5)+3"));
assertTrue(isBalanced("2+(4|(2+3+4)|5)+3"));
assertTrue(isBalanced("(2)+3()"));
assertFalse(isBalanced("(2"));
assertFalse(isBalanced("(2))"));
assertFalse(isBalanced("((2)"));
assertFalse(isBalanced("2|3+3"));
assertFalse(isBalanced("2+(4|5+5)+3"));
assertFalse(isBalanced("2+3|3"));
}

Take different actions depending on jTextField value

I have many more cases, but I'm wondering if there is a simpler way to do this. If the user enters 1 the program will convert from inches to cm, if the user enters 2, the program will convert from cm to feet, etc.
if (jTextField1.getText() == 1) {
InchesToCm();
} else if (jTextField1.getText() == 2) {
CmToFeet();
} else if (jTextField1.getText() == 3) {
MetresToYards();
} else if (jTextField1.getText() == 4) {
KmToMetres();
} else {
jLabel8.setText("Error, try again");
}
It depends on your definition of 'simpler' but you could use a switch statement. Like so:
switch(Integer.parseInt(jTextField1.getText())){
case 1:
InchesToCm();
break;
case 2:
CmToFeet();
break;
case 3:
MetresToYards();
break;
case 4:
KmToMetres();
break;
default:
jLabel8.setText("Error, try again");
break;
}
This way you don't have to use a chain of if statements but if it's simpler is up to you.
I hope this helps :)

How to break out of loop when case is selected

I have a code that has 4 cases and I am trying to break the loop and if the 'f' case is chosen. and then choose from that case. When i try to do the if statement with the break over 30 errors but when I take it away the code is fine.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
}
if (case == 'f')
{
break;
}
}
You would use a Java label (see this code example named BreakWithLabelDemo.java) to tell your code where to break.
myloop:
while ( true ){
switch( choice ){
case 'f':
friendsList();
break myloop;
}
}
For your implementation, it would make sense to break on a specific case before even entering the switch statement. For example:
char choice = one.charAt(0);
if (choice == 'f') break;
switch(choice)
This seems to be a pretty simple way to exit the while loop without conflicting with the break statements of the switch statement.
Or if you still need to call the friendsList method when choice is 'f' you can move that if statement to after the switch statement.
Note: With this you should also remove the if statement at the bottom of your code example.
if (case == 'f')
What is case in this statement? You should replace that with choice.
if (choice == 'f')
you need to put if inside while loop.
String one = "";
boolean yea = true;
Scanner sw = new Scanner(System.in);
while (yea == true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
switch(choice)
{
case 'f':
friendsList();
break;
case 'w':
wall();
break;
case 'p':
network();
break;
case 'q' :
yea = false;
break;
default:
System.out.println("Error: You have entered " + choice +
". Please try again");
}
if (choice == 'f')
{
break;
}
}
The if statement should be moved inside of the while loop to be effective, and case inside the if statement should be changed to choice.
so
While(yea==true)
{
System.out.print(MENU);
one = sw.next();
char choice = one.charAt(0);
if(choice == 'F')
{
break;
}
switch(choice)
{
//cases
}
}

Categories