Java convert else { if {} } to elseif {} - java

I'm looking for any existing code or library in java or a similar language to convert given the following (which is not java, but a custom language)
if (i < 0) {
i = 0;
} else {
if (i > 100) {
i = 100;
}
}
into elseif like this:
if (i < 0) {
i = 0;
} else if (i > 100) {
i = 100;
}
This code is not java but I want to convert it using java.
Here is what I tried to acomplish this but it's not working
String elseB = "else {";
int index = output.indexOf(elseB);
while (index != -1) {
output = output.substring(index + 1);
index = output.indexOf(elseB);
if (index != -1) {
int ifAt = index + elseB.length() + 1;
String elseStart = output.substring(ifAt).trim();
if (elseStart.startsWith("if")) {
int closingBracket = findClosingBracket(
output.toCharArray(), index);
int openingBracket = ifAt - 1;
String justBlock = output.substring(openingBracket,
closingBracket).trim();
output = output.substring(0, openingBracket - 1) + justBlock + output.substring(closingBracket);
}
}
}
a more complicated example would be converting this:
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
} else {
if (i == 4) {
} else {
if (i == 5) {
} else {
if (i == 6) {
} else {
if (i == 7) {
} else {
if (i == 8) {
} else {
if (i == 9) {
} else {
if (i == 10) {
} else {
if (i == 22) {
} else {
if (i == 11) {
} else {
if (i == 12) {
} else {
if (i == 25) {
} else {
if (i == 13) {
} else {
if (i == 14) {
} else {
if (i == 15) {
} else {
if (i == 24) {
} else {
if (i == 16) {
} else {
if (i == 17) {
} else {
if (i == 18) {
} else {
if (i == 21) {
} else {
if (i == 19) {
} else {
if (i == 20) {
} else {
if (i == 23) {
} else {
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
into this
if (i == 1) {
} else if (i == 2) {
} else if (i == 3) {
} else if (i == 4) {
} else if (i == 5) {
} else if (i == 6) {
} else if (i == 7) {
} else if (i == 8) {
} else if (i == 9) {
} else if (i == 10) {
} else if (i == 22) {
} else if (i == 11) {
} else if (i == 12) {
} else if (i == 25) {
} else if (i == 13) {
} else if (i == 14) {
} else if (i == 15) {
} else if (i == 24) {
} else if (i == 16) {
} else if (i == 17) {
} else if (i == 18) {
} else if (i == 21) {
} else if (i == 19) {
} else if (i == 20) {
} else if (i == 23) {
} else {
}

I assume you want to change the code, not the compiled bytecode. For that you would look into text replacing. Depending on your editor you can replace all the instances of this text with the elif statement. If your editor can not do it, look into regular expressions. With those you can change the lines in no time.

If trying to test a single value vs various conditions,could try to use switch statemenet instead various if statements.
ie.
switch(i){
case(i <= 0):
i=0;
case(i >= 100):
i=100;
}

Related

Null pointer exception when referencing an object

I'm writing a dice roller program for a project, and it prints an error when I try to access the Calculations object. Everything else works, from what I can tell (the variables are set correctly, everything prints in order.
Calculations c;
int stage = 0;
int number;
int die;
int mod;
int modnum;
int inc = 0;
int[] num = new int[20];
boolean plusminus;
int spot = 0;
void setup() {
startScreen(inc);
}
void draw() {
}
//initial prompt screen
void startScreen(int stage) {
switch(stage) {
case 0:
println("How many dice? (up to 9)");
break;
case 1:
number = num[spot];
//noLoop();
println("Modifiers? (press + or -)");
break;
case 2:
mod = num[spot];
if (mod == 10) {
plusminus = true;
}
if (mod == 11) {
plusminus = false;
}
//noLoop();
println("how much?");
//loop();
break;
case 3:
modnum = num[spot];
//noLoop();
println("which dice? (1 = d2, 2 = d3, 3 = d4, 4 = d6, 5 = d8, 6 = d10, 7 = d12, 8 = d20, 9= d100");
break;
case 4:
die = num[spot];
c.finalcalc();
break;
}
}
void keyPressed() {
if (keyPressed) {
if (keyCode == ENTER) {
inc++;
loop();
startScreen(inc);
noLoop();
}
if (keyCode != ENTER) {
if (key == '1') {
num[spot] = 1;
println(num[spot]);
} else if (key == '2') {
num[spot] = 2;
println(num[spot]);
} else if (key == '3') {
num[spot] = 3;
println(num[spot]);
} else if (key == '4') {
num[spot] = 4;
println(num[spot]);
} else if (key == '5') {
num[spot] = 5;
println(num[spot]);
} else if (key == '6') {
num[spot] = 6;
println(num[spot]);
} else if (key == '7') {
num[spot] = 7;
println(num[spot]);
} else if (key == '8') {
num[spot] = 8;
println(num[spot]);
} else if (key == '9') {
num[spot] = 9;
println(num[spot]);
} else if (key == '+') {
num[spot] = 10;
println(num[spot]);
} else if (key == '-') {
num[spot] = 11;
println(num[spot]);
}
}
}
}
class Calculations {
int dice() {
int i = 0;
if (die == 1) {
i = round(random(2));
}
if (die == 2) {
i = round(random(3));
}
if (die == 3) {
i = round(random(4));
}
if (die == 4) {
i = round(random(6));
}
if (die == 5) {
i = round(random(8));
}
if (die == 6) {
i = round(random(10));
}
if (die == 7) {
i = round(random(12));
}
if (die == 8) {
i = round(random(20));
}
if (die == 9) {
i = round(random(100));
}
return i;
}
int finalcalc() {
int[] roll = new int[key];
int result = 0;
for (int i = 0; i > roll.length; i++) {
roll[i] = dice();
if (plusminus == true) {
result = dice() + modnum;
}
if (plusminus == false) {
result = dice() - modnum;
}
}
return result;
}
}
I've made sure that my arrays are initialized properly, and I made sure that each of my variables are being referenced correctly, but this hasn't changed anything. I'm not sure what else I need to do.
Here is the error:
java.lang.NullPointerException: Cannot invoke "Final_Project$Calculations.finalcalc()" because "this.c" is null
at Final_Project.startScreen(Final_Project.java:68)
at Final_Project.keyPressed(Final_Project.java:80)
It's missing : Calculations c= new Calculations();

Condtional statements using Calendar.HOUR_OF_DAY

I have this code and it has to show one of the strings based on the time of the day.
The code is
public void onTimeTick() {
mTime.setTimeInMillis(System.currentTimeMillis());
// Let's see what string we need according to the time
int saluteResId = R.string.salute_fallback;
if (mTime.get(Calendar.HOUR_OF_DAY) > 4) {
saluteResId = R.string.salute_morning;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 12) {
saluteResId = R.string.salute_evening;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 19 || mTime.get(Calendar.HOUR_OF_DAY) < 5) {
saluteResId = R.string.salute_night;
}
}
But the problem is that HOUR_OF_DAY will always remain greater than 4 so it will never even check the remaining two conditions and the string will always be set to salute_morning. I am not very good in java and trying to figure out how I can make the first condition false so it will check the other conditions and set the string according to them.
I think this can be helpful
if (mTime.get(Calendar.HOUR_OF_DAY) > 4 && mTime.get(Calendar.HOUR_OF_DAY) <= 12) {
//saluteResId = R.string.salute_morning;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 12 && mTime.get(Calendar.HOUR_OF_DAY) <= 19) {
//saluteResId = R.string.salute_evening;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 19 && mTime.get(Calendar.HOUR_OF_DAY) <= 4) {
//saluteResId = R.string.salute_night;
}
Try this code
final Calendar d = Calendar.getInstance();
final int hh = d.get(Calendar.HOUR_OF_DAY);
//try this way
String time = null;
if (hh == 0) {
time =("Salute_Night");
} else if (hh == 1) {
time =("Salute_Night");
} else if (hh == 2) {
time =("Salute_Night");
} else if (hh == 3) {
time =("Salute_Night");
} else if (hh == 4) {
time =("Salute_Night");
} else if (hh == 5) {
time =("Salute_Morning");
} else if (hh == 6) {
time =("Salute_Morning");
} else if (hh == 7) {
time =("Salute_Morning");
} else if (hh == 8) {
time =("Salute_Morning");
} else if (hh == 9) {
time =("Salute_Morning");
} else if (hh == 10) {
time =("Salute_Morning");
} else if (hh == 11) {
time =("Salute_Morning");
} else if (hh == 12) {
time =("Salute_Evening");
} else if (hh == 13) {
time =("Salute_Evening");
} else if (hh == 14) {
time =("Salute_Evening");
} else if (hh == 15) {
time =("Salute_Evening");
} else if (hh == 16) {
time =("Salute_Evening");
} else if (hh == 17) {
time =("Salute_Evening");
} else if (hh == 18) {
time =("Salute_Evening");
} else if (hh == 19) {
time =("Salute_Evening");
} else if (hh == 20) {
time =("Salute_Night");
} else if (hh == 21) {
time =("Salute_Night");
} else if (hh == 22) {
time =("Salute_Night");
} else if (hh == 23) {
time =("Salute_Night");
}
//your text view where you want it to display
textviewTimeOfDay.settext.(time);

Why won't an IF statement work with rounded floats and doubles?

I am trying to check if a user has inputted a double between 3.5 and 7. I have tried to use the actual double and Math.round();, as well as StrictMath.round(). I have also tried to parse the string inputted as a float but it didn't change anything. Here is the basic code I used:
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
double number = input.nextDouble();
if (isDouble(number)==true) {
double x = Double.parseDouble(number);
if (3.5 <= x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
public static booleen isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1)
|| exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
}
}
I have also tried making 3.5 3 in the if statement but got no dice. I just need a loose explanation and not a full solution.
I've edited your code.
boolean spelling
isDouble() takes a String
a <= x <= b chained expressions are not allowed in Java
Also,
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1) || exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
can be simplified to
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
Here's the full code.
class Test {
public static boolean isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
}
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
String number = input.nextLine();
if (isDouble(number)) {
double x = Double.parseDouble(number);
if (3.5 <= x && x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
}

best practice of compare a map of metadata with an object?

I have a map of metadata and Expression class:
Map<String , Object> metaDate;
public class Expression{
private List<UserCondition> conditions;
private LogicalOperationEnum; // and , or
getters/stters...
}
public classUserCondition{
private String fieldName;
private MathOperationEnum operation; // > , < , >= , <= , =
private Object value;
getters/setters...
}
Now I hav a method this method in my businessService class:
private boolean evaluate(Map<String, Object> userMetaData, Expression expression) {
if (expression.getLogicalOperation() == LogicalOperationEnum.and) {
for (UserCondition c : expression.getConditions()) {
if (c.getOperation().getName() == ">" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) <= 0) {
return false;
} else if (c.getOperation().getName() == "<" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) >= 0) {
return false;
} else if (c.getOperation().getName() == "<=" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) > 0) {
return false;
} else if (c.getOperation().getName() == ">=" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) < 0) {
return false;
} else{
return true;
}
}
} else if (expression.getLogicalOperation() == LogicalOperationEnum.or) {
for (UserCondition c : expression.getConditions()) {
if (c.getOperation().getName() == ">" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) > 0) {
return true;
} else if (c.getOperation().getName() == "<" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) < 0) {
return true;
} else if (c.getOperation().getName() == "<=" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) <= 0) {
return true;
} else if (c.getOperation().getName() == ">=" && String.valueOf(userMetaData.get(c.getField())).compareTo(String.valueOf(c.getValue())) >= 0) {
return true;
}
}
}
return false;
}
Now i think that this method can implement better than , but i don't know how can i do that?

trouble with yahtzee in java

I have to create the yahtzee game and its methods like full house, small straight, big straight, 3 of kind, 4 of kind , and chance. Now this is what i have done so far and i would like to know if my methods are right and also i'm having a hard time trying to figure out how to check if its yahtzee , 3 of kind, 4 of kind , etc and this is in my main method. The program consists of seven rolls, where every roll can have up to two sub-rolls
static final int NUM_RERROLS_ = 2;
static final int NUM_OF_DICE = 5;
static final int NUM_ROLLS_ = 7;
static final int[] dice = new int[NUM_OF_DICE];
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
rollDice();
for (int i = 0; i < NUM_RERROLS_; i++) {
if (gotYatzee()) {
break;
}
System.out.println(diceToString());
askUser();
System.out.println("Which dice do you want to reroll: ");
secondReroll(convert(keyboard.nextLine()));
}
System.out.println(diceToString());
if (gotYatzee()) {
System.out.println("You got Yatzee & 50 points!");
} else if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
{
System.out.println("SORRY NO YAHTZEE");
}
if (askUser() == false) {
if (largeStraight() == true) {
System.out.println("You got large straight");
} else {
System.out.println("Sorry no large straight");
}
if (smallStraight() == true) {
System.out.println("You got smallStraight");
} else {
System.out.println("Sorry no small straight");
}
if (fullHouse() == true) {
System.out.println("You got full house");
} else {
System.out.println("Sorry no full house");
}
}
}
public static void rollDice() {
for (int i = 0; i < NUM_OF_DICE; i++) {
dice[i] = randomValue();
}
}
public static int randomValue() {
return (int) (Math.random() * 6 + 1);
}
public static String diceToString() {
String dado = "Here are your dice: ";
for (int element : dice) {
dado = dado + element + " ";
}
return dado;
}
public static boolean gotYatzee() {
for (int element : dice) {
if (element != dice[0]) {
return false;
}
}
return true;
}
public static void secondReroll(int[] newValue) {
for (int element : newValue) {
dice[element - 1] = randomValue();
}
}
public static int[] convert(String s) {
StringTokenizer st = new StringTokenizer(s);
int[] a = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
a[i++] = Integer.parseInt(st.nextToken());
}
return a;
}
public static boolean Chance() {
for (int element : dice) {
int i = 0;
if (element != dice[i]) {
i++;
return false;
}
}
return true;
}
public static boolean smallStraight() {
for (int i = 1; i <= NUM_OF_DICE; i++) {
boolean b = false;
for (int j = 0; j < NUM_OF_DICE; j++) {
b = b || (dice[j] == i);
}
if (!b) {
return false;
}
}
return true;
}
public static boolean largeStraight() {
int[] i = new int[5];
i = dice;
sortArray(i);
if (((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5))
|| ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6))
|| ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4) && (i[5] == 5))
|| ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5) && (i[5] == 6))) {
return true;
} else {
return false;
}
}
public static boolean askUser() {
Scanner keyboard = new Scanner(System.in);
int a = 0;
String yes = "Yes";
String no = "No";
System.out.println("Do you want to reroll the dice again: Yes or No? ");
String userInput;
userInput = keyboard.next();
if (userInput.equals(yes)) {
System.out.println("ALRIGHTY!!");
return true;
} else if (userInput.equals(no)) {
}
return false;
}
public static boolean threeKind() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) // Three of a Kind
|| ((a[1] == a[2]) && ((a[2] == a[3])
|| (((a[2] == a[3]) && (a[3] == a[4]))))))) {
return true;
} else {
return false;
}
}
/*public static boolean fourKind(int[] dice) {
}
*/
public static int[] sortArray(int[] numbers) {
int stop;
for (stop = 0; stop < numbers.length; stop++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
swap(numbers, i, i + 1);
}
}
}
return numbers;
}
public static void swap(int[] numbers, int pos1, int pos2) {
int temp = numbers[pos1];
numbers[pos1] = numbers[pos2];
numbers[pos2] = temp;
}
public static boolean fullHouse() {
int[] a = new int[5];
a = dice;
sortArray(a);
if ((((a[0] == a[1]) && (a[1] == a[2])) && // Three of a Kind
(a[3] == a[4]) && // Two of a Kind
(a[2] != a[3]))
|| ((a[0] == a[1]) && // Two of a Kind
((a[2] == a[3]) && (a[3] == a[4])) && // Three of a Kind
(a[1] != a[2]))) {
return true;
} else {
return false;
}
}
}
basically i want to figure out a way to check if its full house, 3 of kind, 4 of kind , etc
You have 6 dice after three rolls. Sort the array of user-retained dice after the 3 rolls.
Yahtzee: ((die[0] == die[4]) || (die[1] == die[5]))
4 of a kind: ((die[0] == die[3]) || (die[1] == die[4] || (die[2] == die[5]))
Small straight, 3 tests (x = 3,4,5): ((die[x] - die[x-3]) == 3)
Large straight, 2 tests (x = 4,5): ((die[x] - die[x-4]) == 4)
etc.
Chance: Up to the user, right?
Unless I'm missing something (I'm a little rusty on Yatzee), this should be fairly straightforward.

Categories