Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i want to know how could i can this code into the switch statement
i want to do this if else statement into the switch statement please help me out to find out what i have to do for changing this code into switch statement.
if (board[r - 1][c] == ' ' && board[r][c - 1] == ' ') {
nextRow = r;
nextCol = c - 1;`enter code here`
return true;
}
// We will try to move the cell up.
if (board[r - 1][c] == ' ') {
nextRow = r - 1;
nextCol = c;
return true;
}
// We will try to move the cell to the right.
else if (board[r][c + 1] == ' ') {
nextRow = r;
nextCol = c + 1;
return true;
}
// We will try to move the cell to the left.
else if (board[r][c - 1] == ' ') {
nextRow = r;
nextCol = c - 1;
return true;
}
// We will try to move the cell down.
else if (board[r + 1][c] == ' ') {
nextRow = r + 1;
nextCol = c;
return true;
}
System.out.println("Error due to Array Bound Index");
return false;
}
You can't convert it to a switch, because you aren't picking what to do on the basis of a single value, and your conditions are not mutually exclusive.
However, you can convert the four ifs into a loop:
for (int a = 0; a < 4; ++a) {
int dr = (a & 1 == 0) ? 0 : (a & 2 == 0) ? 1 : -1;
int dc = (a & 2 == 0) ? 0 : (a & 1 == 0) ? 1 : -1;
if (board[r + dr][c + dc] == ' ') {
nextRow = r + dr;
nextCol = c + dc;
return true;
}
}
It seems you are not checking the same value with each if-else, so it would not be possible to write with a switch. A switch statement checks one variable to see if it fits given values.
Here is the switch statement documentation for more info https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You can't convert this to switch statement because you don't check one value. For switch statements code must be like this:
int a = 0;
if (a == 0) {
...
}
else if (a == 1) {
...
}
else if (a == 2) {
...
}
...
and switch statement:
switch (a) {
case 0:
...
break;
case 1:
...
break;
case 2:
...
break;
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
When I submit my code to Leetcode, it reported runtime error as:
Runtime Error Message: Line 8: java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
I tested that case in my local, it works fine. I thought it maybe causeed by the platform and compiler are different. I then tried to test it on Leetcode Playground. It also worked very well.
The Leetcode problem is:https://leetcode.com/problems/string-to-integer-atoi/
I would be very appreciated if anyone could let me know what's wrong with my code.
class Solution{
public int myAtoi(String str) {
if (str == null || str.length() == 0) return 0;
char chs[] = str.toCharArray();
long base = 0;
int i = 0, sign = 1;
while (chs[i] == ' ' && i < str.length()){
i++;
}
if(i == str.length()){
return 0;
}
if (chs[i] == '-') {
i++;
sign = -1;
} else if (chs[i] == '+') {
i++;
}
while (i < str.length() && (chs[i] >= '0' && chs[i] <= '9')) {
base = base * 10 + (chs[i] - '0');
if (sign * base > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (sign * base < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int)(sign * base);
}
}
If pass empty string (one space or more) to myAtoi(" ") in while statement you will go beyond the boundaries of the array:
// chs = {' '}; chs.length = 1; i = 0;
while (chs[i] == ' ') {
i++;
}
You can add an additional condition i < chs.length to while loop:
while (i < chs.length && chs[i] == ' ')
screenshot with result
I'd need some help with Java here...
I have to implement a DFA in Java that recognizes Java comments contained between /* and */.
In order to start with simple things, let's say that DFA's alphabet is: {'/', '*', 'a'}, so it recognizes only those 3 elements.
Possible accepted Strings:
1) /**/
2) /****/
3) /*a*a**/
4) /*a**/
It won't accept:
1) /*/
2) /**/***/
In order to achieve that I developed this method:
public static boolean scan(String s){
int i = 0, state = 0;
while(i < s.length() && stato >= 0){
final char ch = s.charAt(i++);
switch(state){
case 0:
if(ch == '/')
state = 1;
else
state = -1;
break;
case 1:
if(ch == '*')
state = 2;
else
state = -1;
break;
case 2:
if(ch == 'a')
state = 2;
else if(ch == '/')
state = 3;
else
state = -1;
break;
case 3:
if(ch == '*')
state = 4;
else
state = -1;
break;
case 4:
if(ch == ' ')
state = 4;
else
state = -1;
break;
}
}
System.out.println("State: " + state);
return state == 4;
}
But with simplest input /**/ status variable is -1, when it should be 4.
Which changes should I make?
Hope you guys can help me...
Thank you
In Step 3 your state became -1. then how you get matching.
See this block:
case 2:
if(ch == 'a')
state = 2;
else if(ch == '/')
state = 3;
else
state = -1;
break;
State 0 : char / : nextState 1
State 1 : char * : nextState 2
State 2 : char * : nextState -1
State -1 : char / : nextState -1
I need help with evaluating arithmetic expression (INFIX) via recursion. I made a tree, scanning from right to left (+,- first, *,/ second). The error is:
For input string: "2+3"
I don't what I'm doing wrong. I was hoping if someone can look at my method and point me to right direction please. Appreciate the help. Here is my method.
// recursive method to evaluate an expression given by string s
int evaluateE(String s)
{
String r1;
String r2;
int result = 0;
int i;
for(i = s.length() - 1; i >= 0; i--)
{
if (s.charAt(i) == '+' || s.charAt(i) == '-')
break;
else if (s.charAt(i) == '*' || s.charAt(i) == '/')
break;
}
r1 = s.substring(0, i);
r2 = s.substring(i + 1, s.length());
//Base case
if(!r1.contains("+") && !r1.contains("-") && !r1.contains("*") && !r1.contains("/") &&
!r2.contains("+") && !r2.contains("-") && !r2.contains("*") && !r2.contains("/"))
return Integer.parseInt(s);
switch (s.charAt(i))
{
case '+':
result = evaluateE(r1) + evaluateE(r2);
break;
case '-':
result = evaluateE(r1) - evaluateE(r2);
break;
case '*':
result = evaluateE(r1) * evaluateE(r2);
break;
case '/':
if (Integer.parseInt(r2) == 0) //if denominator is zero
{
System.out.println("Invalid divisor");
System.exit(1);
}
else
result = evaluateE(r1) / evaluateE(r2);
break;
}
return result;
}
You're checking the operators, if they contain an operator, i.e. for r1+r2 you check, if r1 or r2 contain a operator. If your String contains exactly 1 operator, neither r1 nor r2 contain a operator and therefore Integer.parse(s) will be executed. Since s = r1 + operator + r2 contains the operator, Integer.parse will throw an error.
To fix this, check the base case before doing anything else in that method:
int evaluateE(String s) {
//Base case
if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/")) {
return Integer.parseInt(s);
}
int i;
for (i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
break;
} else if (s.charAt(i) == '*' || s.charAt(i) == '/') {
break;
}
}
String r1 = s.substring(0, i);
String r2 = s.substring(i + 1, s.length());
int result = 0;
switch (s.charAt(i)) {
case '+':
result = evaluateE(r1) + evaluateE(r2);
break;
case '-':
result = evaluateE(r1) - evaluateE(r2);
break;
case '*':
result = evaluateE(r1) * evaluateE(r2);
break;
case '/':
int right = evaluateE(r2);
if (right == 0) //if denominator is zero
{
System.out.println("Invalid divisor");
System.exit(1);
} else {
result = evaluateE(r1) / right;
}
break;
}
return result;
}
That ignores operator precedence however, i.e. it evaluates expressions from left to right. E.g. 10-3*6/9+4 is interpreted as (((10-3)*6)/9)+4.
If you want to take operator precedence into accout, you have to ignore * or /, if there is a + or a - in the string. This would require you to modify your for loop:
// search for '+' and '-' first
for (i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
break;
}
}
if (i < 0) {
// if '+' and '-' were not found, search for '*' and '/'
for (i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '*' || s.charAt(i) == '/') {
break;
}
}
}
It is not clear why you are returning Integer.parseInt(s) when in all likelihood s will have an operator (+,-,* or /). So, essentially you are trying to convert "2+3" into an int, which is the reason for the error.
SO im making a program the will solve a maze recursively and im having problems with my
if else statements. I had a similar problem in a different part of my code and i solved it by just taking out all the else's and just having a bunch of if statements. But now i need it the stop searching after it finds the correct way to go.
public static void solveMaze(int ROW, int COL){
int isFinished = 0;
//ROW COL
//set up base case. find end if possible to get in 1 move then end
if(drawArray[ROW][COL+1] == ' '){
if(drawArray[ROW][COL+2] == 'E'){
isFinished = 1;
move(ROW,COL,ROW,COL+2);
}
}
if(drawArray[ROW][COL-1] == ' '){
if(drawArray[ROW][COL-2] == 'E'){
isFinished = 1;
move(ROW,COL,ROW,COL-2);
}
}
if(drawArray[ROW+1][COL] == ' '){
if(drawArray[ROW+2][COL] == 'E'){
isFinished = 1;
move(ROW,COL,ROW+2,COL);
}
}
if(drawArray[ROW-1][COL] == ' '){
if(drawArray[ROW-2][COL] == 'E'){
isFinished = 1;
move(ROW,COL,ROW-2,COL);
}
}
//find first open cell and choose it
int foundOpen = 0;
if(isFinished == 0){
if(drawArray[ROW][COL+1] == ' ' && drawArray[ROW][COL+2] != '*'){
drawArray[ROW][COL+2] = '*';
prevCol = COL;
prevRow = ROW;
COL+= 2;
foundOpen = 1;
}
else if(drawArray[ROW+1][COL] == ' ' && drawArray[ROW+2][COL] != '*'){
drawArray[ROW+2][COL] = '*';
prevCol = COL;
prevRow = ROW;
ROW+= 2;
foundOpen = 1;
}
else if(drawArray[ROW][COL-1] == ' ' && drawArray[ROW][COL-2] != '*'){
drawArray[ROW][COL-2] = '*';
prevCol = COL;
prevRow = ROW;
ROW-= 2;
foundOpen = 1;
}
else if(drawArray[ROW-1][COL] == ' ' && drawArray[ROW-2][COL] != '*'){
drawArray[ROW-2][COL] = '*';
prevCol = COL;
prevRow = ROW;
ROW-= 2;
foundOpen = 1;
}
}
//i have two recursive voids so this is chosing between them
if(foundOpen == 1){
move(prevRow,prevCol,ROW,COL);
solveMaze(ROW,COL);}
else if (foundOpen == 0 && isFinished == 0)
wrongChoice(ROW, COL);
}
SO basically this part of the program checks to see first if the end is near and if it is basically finish. I use to have if else statements for the first part to but i wouldnt work and the only way i could fix it was by taking out the else's. So in one maze that i have to solve the first move should be COL-1 == ' ' and COL-2 != '*'. so that if statement should happen but it doesnt. I put in a bunch of println statements to check where it was going off and isFInished == 0 so it starts into that if statement but then something goes wrong and nothing solution is found so wrongChoice is called. Im prety new to java and recursion so i might be missing something obvios.
boolean isFinished = true;
if (drawArray[ROW][COL+1] == ' ' && drawArray[ROW][COL+2] == 'E') {
move(ROW,COL,ROW,COL+2);
} else if (drawArray[ROW][COL-1] == ' ' && drawArray[ROW][COL-2] == 'E') {
move(ROW,COL,ROW,COL-2);
} else if (drawArray[ROW+1][COL] == ' ' && drawArray[ROW+2][COL] == 'E') {
move(ROW,COL,ROW+2,COL);
} else if (drawArray[ROW-1][COL] == ' ' && drawArray[ROW-2][COL] == 'E') {
move(ROW,COL,ROW-2,COL);
} else {
isFinished = false;
}
int foundOpen = 0;
if (!isFinished) {
That should do.
If you do this kind of looking at naybors more often:
static final int[][] naybors = {
{ 0, 1 },
{ 0, -1 },
{ 1, 0 },
{ -1, 0 },
};
boolean isFinished = false;
for (int[] nb : naybors) {
if (drawArray[ROW + nb[0]][COL + nb[1]] == ' '
&& drawArray[ROW + 2*nb[0]][COL + 2*nb[1]] == 'E') {
move(ROW, COL, ROW + 2*nb[0], COL + 2*nb[1);
isFinished = true;
break;
}
}
Also saw:
else if(drawArray[ROW][COL-1] == ' ' && drawArray[ROW][COL-2] != '*'){
drawArray[ROW][COL-2] = '*';
prevCol = COL;
prevRow = ROW;
//Wrong: ROW-= 2;
COL -= 2; // Good?
foundOpen = 1;
}
you could System.out.print and check where you want it to stop then use #mserioli suggestion which will work. good luck
This question already has answers here:
Conditional statement true in both parts of if-else-if ladder
(4 answers)
Closed 2 years ago.
For those who don't know, FizzBuzz is the following problem:
Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".
Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:
for(int i = 1; i <= 100; i++) {
if (i % 3 == 0)
System.out.print("Fizz");
if (i % 5 == 0)
System.out.println("Buzz")
else
System.out.println(i);
}
But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?
What you're trying to do is
if (a)
...
if (b)
...
else // if neigther a nor b
...
This is simply not possible. An else can only belong to a single if. You have to go with the slightly longer variant.
To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as
boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;
if (fizz)
System.out.print("Fizz");
if (buzz)
System.out.print("Buzz");
if (!(fizz || buzz))
System.out.print(i);
System.out.println();
Another one would be
String result = "";
if (i % 3 == 0) result = "Fizz";
if (i % 5 == 0) result += "Buzz";
if (result == "") result += i;
System.out.println(result);
Your first if statement is all alone.
So, your code hits the first statement, which is ONLY an if statement, and then goes on to the next, which is an if/else statement.
RosettaCode has a good example without using AND operators.
int i;
for (i = 0; i <= 100; i++) {
if ((i % 15) == 0)
cout << "FizzBuzz" << endl;
else if ((i % 3) == 0)
cout << "Fizz" << endl;
else if ((i % 5) == 0)
cout << "Buzz" << endl;
else
cout << i << endl;
}
If your only goal is to avoid using &&, you could use a double negation and DeMorgan's laws:
for(int i = 1; i <= 100; i++) {
if(!(i % 3 != 0 || i % 5 != 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
You can avoid && using the fact that i % 3 == 0 and i % 5 == 0 implies i % 15 == 0, as per RFC1337's answer.
Another solution is to use a switch on the remainder (mod 15, which is 5 times 3):
for(int i = 1; i <= 100; i++) {
final int mod = i % 15;
switch (mod) {
case 0:
case 3:
case 6:
case 9:
case 12:
System.out.print("Fizz");
if (mod != 0) break;
case 5:
case 10:
System.out.print("Buzz");
break;
default:
System.out.print(i);
}
System.out.println();
}
This is my solution. Granted, it's a bit convoluted (as in roundabout), but I believe it suits your requirement.
int main()
{
char fizzpass=0;
unsigned short index=0;
for(index=1;index<=100;index++)
{
if(0 == (index%3))
{
printf("Fizz");
fizzpass = 1;
}
if(0 == (index%5))
{
if(1 == fizzpass)
{
fizzpass = 0;
}
printf("Buzz\n");
continue;
}
if(1 == fizzpass)
{
fizzpass = 0;
printf("\n");
continue;
}
printf("%d\n",index);
}
return 0;
}
Regards.
Just add a flag variable and use System.out.print:
package com.stackoverflow;
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean printed = false;
if (i % 3 == 0) {
printed = true;
System.out.print("Fizz");
}
if (i % 5 == 0) {
printed = true;
System.out.print("Buzz");
}
if (printed) {
System.out.println();
} else {
System.out.println(i);
}
}
}
}
This doesn't take out the if statements but does not use the && (and) operator, you could flip the binary operators.
//FizzBuzz Case
if(!(a % 3 != 0 || a % 5 != 0)){ //flips
result[index] = "FizzBuzz";
index++;
}
Don't use an if statement at all.
import java.util.*;
import java.lang.*;
import java.io.*;
class FizzBuzz
{
public static void main (String[] args) throws java.lang.Exception
{
String[] words = {"", "Fizz", "Buzz"};
String[] nwords = {"", ""};
for(int i = 1; i < 101; ++i)
{
int fp = (i % 3 == 0) ? 1 : 0;
int bp = ((i % 5 == 0) ? 1 : 0) * 2;
int np = ((fp > 0 || bp > 0) ? 1: 0);
nwords[0] = Integer.toString(i);
System.out.print(words[fp]);
System.out.print(words[bp]);
System.out.println(nwords[np]);
}
}
}
See it on ideone.
public class fizzbuzz
{
public static void main(String[] args)
{
String result;
for(int i=1; i<=100;i++)
{
result=" ";
if(i%3==0)
{
result=result+"Fizz";
}
if(i%5==0)
{
result=result+"Buzz";
}
if (result==" ")
{
result=result+i;
}
System.out.println(result);
}
}
}
This is the most efficient way I could come up with. Hope it helps! :)
Crazy albeit unrelated solution done in Python3
#!/usr/bin/python3
for i in range(1,100):
msg = "Fizz" * bool(i%3==0)
msg += "Buzz" * bool(i%5==0)
if not msg:
msg = i
print(msg)