Why switch statement in not comparing the int values? - java

**I wrote a simple code that have to compare to numbers, but when I run it compiler say me that has a error with boolean values. I dont understand why it doesnt work **
{
public static void main(String[] args) {
compare(8,22);
}
static void compare(int a, int b){
switch (a) {
case (a > b) -> System.out.println(a + " > " + b);
case (b < a) -> System.out.println(a + " < " + b);
case (a == b) -> System.out.println(a + " = " + b);
default -> System.out.println("Something is wrong !");
}
}
}```

Change it to:
{
public static void main( String... args )
{
compare( 8, 22 );
}
static void compare( final int a, final int b )
{
switch( Integer.signum( Integer.compare( a, b ) ) )
{
case 1 -> System.out.println( a + " > " + b );
case -1 -> System.out.println( a + " < " + b );
case 0 -> System.out.println( a + " = " + b );
default -> System.out.println( "Something is wrong !" );
}
}
}
And it should work!
case requires distinct constant expressions, and the terms that you use ((a > b), (b < a) and (a == b)) are no constants (not to mention that (a > b) and (b < a) are equivalent). They also return a boolean. switch does not handle a boolean switch selector directly.
In JShell, (only) this works for switch with "boolean":
boolean flag = …
switch( Boolean.toString( flag ) )
{
case "true" -> …
case "false" -> …
default -> throw new Error( "Hä?" );
}

Related

Creating truth tables for propositional logic formulas?

I wanted to create a program that, given a logic formula by the user, for example ((¬A ∧ B) ∨ C) ∧ A, calculates its truth table.
In this case the formula would be true if A=1, B=0, C=1, or if A=1, B=1, C=1, and it would be false in any other case.
But, I don't know how to create a method that can read the expression given, and then calculate all the possible outcomes.
I don't know how to create a method that can read the expression given, and then calculate all the possible outcomes.
OK, so let's start with the task breakdown into subtasks.
Here's what you need to do ...
Parse the string you get as input into some internal data structures used by your program. This is a hard task. Make sure to cover relevant methods by unit tests.
Calculate the truth tables. This is easier. You just need to iterate over all possible sets of inputs. These will be binary numbers from 0 to 2^n-1 where n is the number of boolean inputs.
Let's see what resources you can use ...
For the parse part you can adapt this
To generate all possible inputs you can use this
Also, please, make sure to cover your methods by unit tests. Its easy to make a mistake in complicated logic like this, which will take hours to debug. Therefore, unit tests will save you loads of time.
Does this solve your problem ? Tell me in the comments.
Try this.
interface Bool {
boolean get();
default Bool and(Bool r) { return () -> get() ? r.get() : false; }
default Bool or(Bool r) { return () -> get() ? true : r.get(); }
default Bool not() { return () -> !get(); }
}
static class TruthTable {
String formula;
int index, ch;
List<Character> variables;
Map<Character, Boolean> map;
Bool bool;
int get() {
return ch = index < formula.length() ? formula.charAt(index++) : -1;
}
boolean match(int expect) {
if (ch == expect) {
get();
return true;
}
return false;
}
Bool element() {
Bool b;
if (match('(')) {
b = expression();
if (!match(')'))
throw new RuntimeException("')' expected");
} else if (Character.isAlphabetic(ch)) {
char v = (char) ch;
get();
if (!variables.contains(v))
variables.add(v);
b = () -> map.get(v);
} else
throw new RuntimeException("unknown char: " + (char) ch);
return b;
}
Bool factor() {
if (match('¬'))
return element().not();
return element();
}
Bool term() {
Bool b = factor();
while (match('∧'))
b = b.and(factor());
return b;
}
Bool expression() {
Bool b = term();
while (match('∨'))
b = b.or(term());
return b;
}
String str(boolean b) {
return b ? "T" : "F";
}
void print() {
for (char v : variables)
System.out.print(str(map.get(v)) + " ");
System.out.println(str(bool.get()));
}
void test(int i) {
if (i >= variables.size())
print();
else {
char c = variables.get(i);
map.put(c, true);
test(i + 1);
map.put(c, false);
test(i + 1);
}
}
public void make(String formula) {
this.formula = formula.replaceAll("\\s", "");
index = 0;
variables = new ArrayList<>();
map = new HashMap<>();
get();
bool = expression();
if (ch != -1)
throw new RuntimeException(
"extra string '" + formula.substring(index - 1) + "'");
for (char v : variables)
System.out.print(v + " ");
System.out.println(formula);
test(0);
System.out.println();
}
}
And
public static void main(String[] args) {
new TruthTable().make("¬A");
new TruthTable().make("¬A ∧ B");
new TruthTable().make("(¬A ∧ B) ∨ C");
new TruthTable().make("((¬A ∧ B) ∨ C) ∧ A");
}
output:
A ¬A
T F
F T
A B ¬A ∧ B
T T F
T F F
F T T
F F F
A B C (¬A ∧ B) ∨ C
T T T T
T T F F
T F T T
T F F F
F T T T
F T F T
F F T T
F F F F
A B C ((¬A ∧ B) ∨ C) ∧ A
T T T T
T T F F
T F T T
T F F F
F T T F
F T F F
F F T F
F F F F

Regular Expression for numerals in java

In my application I need filter concept for numeric.So I need to generate dynamic regular expression format.For example if I gave input is like (attrN = number,operator="equal",value=459) and (attrN = number,operator="lessthan equal",value=57) and (attrN = number,operator="not equal",value=45) and (attrN = number,operator="greaterthan equal",value=1000).based on the above conditions need to develop dynamic regular expression.I tried lessthan equal condition but I didn't get union and subtraction also greater than equal conditions.I need the logic or algorithm.
public class NumericRangeRegex {
public String baseRange(String num, boolean up, boolean leading1) {
char c = num.charAt(0);
char low = up ? c : leading1 ? '1' : '0';
char high = up ? '9' : c;
if (num.length() == 1)
return charClass(low, high);
String re = c + "(" + baseRange(num.substring(1), up, false) + ")";
if (up) low++; else high--;
if (low <= high)
re += "|" + charClass(low, high) + nDigits(num.length() - 1);
return re;
}
private String charClass(char b, char e) {
return String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e);
}
private String nDigits(int n) {
return nDigits(n, n);
}
private String nDigits(int n, int m) {
return "[0-9]" + String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m);
}
private String eqLengths(String from, String to) {
char fc = from.charAt(0), tc = to.charAt(0);
if (from.length() == 1 && to.length() == 1)
return charClass(fc, tc);
if (fc == tc)
return fc + "("+rangeRegex(from.substring(1), to.substring(1))+")";
String re = fc + "(" + baseRange(from.substring(1), true, false) + ")|"
+ tc + "(" + baseRange(to.substring(1), false, false) + ")";
if (++fc <= --tc)
re += "|" + charClass(fc, tc) + nDigits(from.length() - 1);
return re;
}
private String nonEqLengths(String from, String to) {
String re = baseRange(from,true,false) + "|" + baseRange(to,false,true);
if (to.length() - from.length() > 1)
re += "|[1-9]" + nDigits(from.length(), to.length() - 2);
return re;
}
public String run(int n, int m) {
return "\\b0*?("+ rangeRegex("" + n, "" + m) +")\\b";
}
public String rangeRegex(String n, String m) {
return n.length() == m.length() ? eqLengths(n, m) : nonEqLengths(n, m);
}
}
Use a simple interface for this
public interface Check {
boolean isValidFor(int value);
}
Then implement different classes for different kind of checks like
public class isEqualTo implements Check {
private int valueToTestAgainst;
public isEqualTo(int test) {
valueToTestAgainst = test;
}
public boolean isValidFor(int value) {
return valueToTestAgainst == value;
}
}
public class isGreatherThan implements Check {
private int valueToTestAgainst;
public isGreatherThan(int test) {
valueToTestAgainst = test;
}
public boolean isValidFor(int value) {
return valueToTestAgainst > value;
}
}
And then have a class that parses the given input and creates a list of Check objects. Maybe create an abstract class to hold the check value (valueToTestAgainst) and/or make the implementation generic to support other types like double.
Based on conditions Ill try for union and subtraction is `^(?!250)0*?([0-9]|2(5([0-5])|[0-4][0-9])|1[0-9]{2}|[1-9][0-9]|2000)$. In this we are matching 1 to 255 range and 2000 numeric number(union) and for negate 250(subtraction).It's working fine.

how to print the parameter name correctly?

the output should be as below:
foo (A, T1, T2) -> void
bar (A, T1, T2, T3) -> int
doo () -> double
public static class A {
void foo(int T1, double T2) { }
int bar(int T1, double T2, char T3) { return 1; }
static double doo() { return 1; }
}
static void displayMethodInfo(Object obj)
{
Class<?> a = obj.getClass();
Method[] methods = a.getDeclaredMethods();
for (Method y : methods) //print methods
{
System.out.print(y.getName() + "(" ); // + y.getDeclaringClass().getSimpleName());
Type[] types = y.getGenericParameterTypes(); //get parameter types
if (!(Modifier.isStatic((y.getModifiers()))))
{
//non-static method, output this class namr as the 1st argument
System.out.print(y.getName()); //display
if (types.length > 0)
{
//put a comma and space
System.out.print(", ");
}
}
for (Type z : types)
System.out.print(", " + z.toString());
System.out.println( ") " + " -> " + y.getGenericReturnType().toString()); //*/
/*
//print parameter of the method
int i = 0;
for (; i < types.length-1; i++)
{
System.out.print(removeClassFromName (types[i].toString()) + ", ");
}
if (types.length > 0) //print last parameter
{
System.out.print(removeClassFromName(types[i].toString()));
//print return type
System.out.println( " ) " + " -> " + removeClassFromName(y.getGenericReturnType().toString()));
} */
}
}
with my code after I run the code, it outputs the code as below, it does not print out the type correctly. how should I fixed and have that output correctly?
bar(int, double, char) -> int
doo() -> double
foo(int, double) -> void
And every time when I recompiled and run it, the output is having the different order.
#Zoe as #Sami Sarraj said, your code is doing what is supposed to. About the order, it is not possible to get the order it was wrote by the getDeclaredMethods() call, as you can see here.
About getting the parameters names you can find a hint here.

Simple instance variable issue

I'm working on a small personal project involving elliptic curves, and I'm having a bit of difficulty with the curve's instance variables. The variables are printed correctly in the main method, but the print method always returns that each variable is equal to 0. Does anyone see a way to fix this? Please bear with me, I know that this is a fairly trivial problem.
public class ellipticcurve {
public int A, B, p;
public ellipticcurve(int A, int B, int p) {
A = this.A;
B = this.B;
p = this.p;
// E:= Y^2 = X^3 + AX + B
}
public static boolean isAllowed(int a, int b, int p) {
return ((4*(Math.pow(a, 3)) + 27*(Math.pow(b, 2)))%p != 0);
}
public static void printCurve(ellipticcurve E) {
System.out.println("E(F" + E.p + ") := Y^2 = X^3 + " + E.A + "X + " + E.B + ".");
}
public static void main(String[] args) {
ArgsProcessor ap = new ArgsProcessor(args);
int a = ap.nextInt("A-value:");
int b = ap.nextInt("B-value:");
int p = ap.nextInt("Prime number p for the field Fp over which the curve is defined:");
while (isAllowed(a, b, p) == false) {
System.out.println("The parameters you have entered do not satisfy the "
+ "congruence 4A^3 + 27B^2 != 0 modulo p.");
a = ap.nextInt("Choose a new A-value:");
b = ap.nextInt("Choose a new B-value:");
p = ap.nextInt("Choose a new prime number p for the field Fp over which the curve is defined:");
}
ellipticcurve curve = new ellipticcurve(a, b, p);
System.out.println(curve.A + " " + curve.B + " " + curve.p);
printCurve(curve);
System.out.println("The elliptic curve is given by E(F" + p
+ ") := Y^2 = X^3 + " + a + "X + " + b + ".");
}
In your constructor it should be in this way.
public ellipticcurve(int A, int B, int p) {
this.A = A;
this.B = B;
this.p = p;
// E:= Y^2 = X^3 + AX + B
}
instead of
public ellipticcurve(int A, int B, int p) {
A = this.A;
B = this.B;
p = this.p;
// E:= Y^2 = X^3 + AX + B
}
You are assigning the instance variable to the variable passed in the constructor so the instance variable will be initialized to their default value

(Java, Bukkit) Using extended class methods don't work (Noob oop)

I have one class named 'Regions', which make region and check if coordinates are in it. Then I have other class 'ArrowTower' which extends 'Region'. Class 'ArrowTower' creates towers. All day I was experimenting with no results. What I want to do is assign first and second location to class 'Regions' then make region and check if coordinates belongs to it. I also have events - 'BlockTouch' class which creates 'ArrowTower' object.. When I try to tower.insideRegion(e.getClickedBlock()); it gives me my location and then zeros, because it didin't set values in public void buildArrowTower, but values are right here. So I just don't understand why this isn't working :/
My Events class:
import eu.anavicius.TomTom1997.TomTowerDefence.Towers.ArrowTower;
public class BlockTouch implements Listener {
#EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
ArrowTower tower = new ArrowTower();
if (e.getAction() == Action.RIGHT_CLICK_BLOCK ) {
if (e.getItem().getType() == Material.ARROW) {
tower.buildArrowTower(e.getClickedBlock(),e.getPlayer());
} else if (e.getItem().getType() == Material.BONE) {
Bukkit.broadcastMessage("Bone");
tower.insideRegion(e.getClickedBlock());
}
}
}
}
My Region.class:
public class Regions {
private int xl,yl,zl,xh,yh,zh;
public void setLRegion (int x, int y, int z) {
xl = x;
yl = y;
zl = z;
//Bukkit.broadcastMessage("SetLMethod" + " \t " + "|" + xl + "|"+ xh + "||" + "|" + yl + "|" + yh + "||" + "|" +zl + "|" + zh + "||");
}
public void setHRegion (int x, int y, int z) {
xh = x;
yh = y;
zh = z;
//Bukkit.broadcastMessage("SetHMethod" + " \t " + "|" + xl + "|"+ xh + "||" + "|" + yl + "|" + yh + "||" + "|" +zl + "|" + zh + "||");
}
public void insideRegion (Block l) {
int x,y,z;
x = l.getX();
y = l.getY();
z =l.getZ();
Bukkit.broadcastMessage("InsideMethod" + " \\t " + x + "|" + xl + "|"+ xh + "||" +y + "|" + yl + "|" + yh + "||" + z + "|" +zl + "|" + zh + "||");
if (x >= xl && x <= xh ) {
Bukkit.broadcastMessage("Region check 1");
if (z >= zl && z <= zh) {
Bukkit.broadcastMessage("Region check 2");
if (y >= yl && y >= yh) {
Bukkit.broadcastMessage("Regione");
}
}
}
}
}
My ArrowTower.class:
public class ArrowTower extends Regions {
public ArrowTower () {
}
public void buildArrowTower (Block b,Player p) {
if (b.getType().equals(Material.EMERALD_BLOCK)) {
Location loc = b.getLocation();
for (int y = 0; y < 4;y++) {
int layloc = 0;
int by = loc.getBlock().getY()+1 + y;
for (int x = 0;x <3;x++) {
int bx = loc.getBlock().getX()-1 + x;
for (int z = 0;z < 3;z++) { // Pagalvot dar del delay, nes su kintamaisiais pirma blogai buvau
int bz = loc.getBlock().getZ()-1 + z; // sugalvojas, atsispausdina tuscios vietos
Location block = new Location(b.getWorld(),bx,by,bz); // pass loop values to method
if (y == 0 && layloc == 0) {
Bukkit.broadcastMessage("SetR L");
setLRegion(bx,by,bz);
} else if (y == 3 && layloc == 8) {
Bukkit.broadcastMessage("SetR H");
setHRegion(bx,by,bz);
}
block.getBlock().setType(Material.matchMaterial(towerl1(y,layloc)));
layloc++;
}
}
}
}
}
public String towerl1(int h, int layloc) {
String[] layer1 = { // - l
"LOG","AIR","LOG",
"AIR","AIR","AIR",
"LOG","AIR","LOG"};
String[] layer2 = { // - i
"COBBLE_WALL","COBBLESTONE","COBBLE_WALL",
"COBBLESTONE","AIR","COBBLESTONE",
"COBBLE_WALL","COBBLESTONE","COBBLE_WALL"};
String[] layer3 = { // - t
"COBBLE_WALL","AIR","COBBLE_WALL",
"COBBLE_WALL","MOSSY_COBBLESTONE","COBBLE_WALL",
"COBBLE_WALL","AIR","COBBLE_WALL"};
String[] layer4 = {
"AIR","AIR","AIR",
"AIR","JACK_O_LANTERN","AIR",
"AIR","AIR","AIR"};
if (h == 0) {
return layer1[layloc];
} else if (h == 1) {
return layer2[layloc];
} else if (h == 2) {
return layer3[layloc];
} else if (h == 3) {
return layer4[layloc];
} else {
return null;
}
}
}
The problem is that you create a new ArrowTower object on each interact event. I assume you first right-click on a block while holding an arrow in your hand - that's when tower.buildArrowTower(e.getClickedBlock(),e.getPlayer()); is called.
Then you take a bone in your hand, and click again - but this time your event handler will create a completely new ArrowTower with it's first line (actually you don't even have a reference to the first one, since it was only declared in the function's scope):
ArrowTower tower = new ArrowTower();
Then you call:
tower.insideRegion(e.getClickedBlock());
but this tower was just created - actually it's xh, yh, etc. values weren't ever initialized.

Categories