Java while loop query [closed] - java

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 4 years ago.
Improve this question
This while code works fine, it is a program to check for palindromes.
public class Solution {
public static boolean checkPalindrome(String str){
int i=0;
int j= str.length()-1;
while(i<j)
{
if(str.charAt(i)!=str.charAt(j))
{
return false;
}
i++;
j--;
}
return true;
}
}
But what will happen in this version, what do you expect the output to be in this?
public class Solution {
public static boolean checkPalindrome(String str){
int i=0;
int j= str.length()-1;
while(i<j)
{
if(str.charAt(i)!=str.charAt(j))
{
return false;
}
else
{
return true;
}
i++;
j--;
}
}
}

In your second code block you are first checking if the first character is the same as the last.
If it isn't, return false.
Else, return true.
So this isn't going to be a valid palindrome check. It only checks if the first and last letters are the same or not and ignores the letters in the middle.

Related

Any one help me to fix valid Sudoku solution code below [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
class Solution {
public static boolean isValidSudoku(char[][] board) {
return sudoku(board,0,0);
}
public static boolean sudoku(char board[][],int row,int col){
//base case
if(row == 9){
return true; //we reached to end means silution exist
}
int nextrow=row;
int nextcol=col+1;
if(col+1==9){
nextrow=row+1;
nextcol=0;
}
// element alraedy present
if(board[row][col] != '.'){
return sudoku(board, nextrow, nextcol);
}
//element not present try to put digits
for(char i='1';i<='9';i++){
//check is safe to input digit
if(isSafeSudoku(board,row,col,i)){
//insert
board[row][col]=i;
//now check solution exist
if(sudoku(board, nextrow, nextcol)){
return true;
}
board[row][col]='.'; //unsafe here don't put element
}
}
return false; //solution not exist
}
public static boolean isSafeSudoku(char[][] board, int row, int col, char digit) {
//check in row
for(int i=0;i<9;i++){
if(board[i][col] == digit){
return false;
}
}
//check in col
for(int i=0;i<9;i++){
if(board[row][i] == digit){
return false;
}
}
//check in grid
int sr=(row/3)*3;
int sc=(col/3)*3;
for(int i=sr;i<sr+3;i++){
for(int j=sc;j<sc+3;j++){
if(board[i][j] == digit){
return false;
}
}
}
return true;
}
}
Input
board =
[[".","8","7","6","5","4","3","2","1"],["2",".",".",".",".",".",".",".","."],["3",".",".",".",".",".",".",".","."],["4",".",".",".",".",".",".",".","."],["5",".",".",".",".",".",".",".","."],["6",".",".",".",".",".",".",".","."],["7",".",".",".",".",".",".",".","."],["8",".",".",".",".",".",".",".","."],["9",".",".",".",".",".",".",".","."]]
4 / 507 testcases passed
Output
false
Expected
true

Bug in java function that finds palindrome [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
leetcode 680 https://leetcode.com/problems/valid-palindrome-ii/ asks to find a palindrome after deleting at most one character from it. I wrote the following code, but it turns out to fail for string "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga" because the r value becomes 80 in the ends program entering the outer else case in which the functions return false. The program has passed the most tests so I'm not sure what's the problem of this program.
public boolean validPalindrome(String s) {
int l = 0, r = s.length() - 1;
boolean deleted = false;
while (l < r) {
System.out.println(s.charAt(l));
if (s.charAt(l) == s.charAt(r)) {
l++;
r--;
} else if (!deleted) {
deleted = true;
if (s.charAt(l + 1) == s.charAt(r)) {
l++;
} else if (s.charAt(l) == s.charAt(r - 1)) {
r--;
} else {
return false;
}
} else {
return false;
}
}
return true;
}
This test fails because you assume that only one of the two conditions in
if (s.charAt(l + 1) == s.charAt(r)) {
l++;
} else if (s.charAt(l) == s.charAt(r - 1)) {
r--;
Is true. In the given test case when l=19 and r=81 both are true so you need to decide which one to apply.
To demonstrate the issue change the order of the two conditions:
if (s.charAt(l) == s.charAt(r-1)) {
r--;
} else if (s.charAt(l+1) == s.charAt(r)) {
l++;
The change does not fix the issue, just demonstrate it.
(You may find this helpful: What is a debugger and how can it help me diagnose problems?)

What are some real-world programming applications of using the binary literal instead of the decimal literal? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
When should we use binary instead of decimal? What are some real life applications of using the binary literal in any programming language?
Bit manipulations. There are many tasks using this.
E.g. you need to check that all switches (e.g. of the light) are on or off. You have many of them (e.g. 32).
You can implement it using boolean array:
class SwitchControl {
private final boolean[] lights = new boolean[32];
public void turnOnLight(int n) {
lights[n] = true;
}
public void turnOffLight(int n) {
lights[n] = false;
}
public boolean isLightOn(int n) {
return lights[n];
}
public boolean isAllLightsOn() {
for (boolean light : lights)
if (!light)
return false;
return true;
}
public boolean isAllLightsOff() {
for (boolean light : lights)
if (light)
return false;
return true;
}
}
But easiest and more efficient implementation is to use int as a holder of 32 bits’ or light switchers`:
class SwitchControl {
private int lights;
public void turnOnLight(int n) {
lights |= 1 << n;
}
public void turnOffLight(int n) {
lights &= ~(1 << n);
}
public boolean isLightOn(int n) {
return (lights & 1 << n) != 0;
}
public boolean isAllLightsOn() {
return lights == 0xFFFFFFFF; // all 32 bits are set
}
public boolean isAllLightsOff() {
return lights == 0; // all 32 bits are cleared
}
}

Why does else if( 2 > 1) { System.out.println(" hello") ;} is not working? [closed]

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 7 years ago.
Improve this question
Problem in infix to postfix conversion
at the point when value fetched is '-' then the compiler does not enter at else-if block (last case)
package com.conversion;
import java.util.Scanner;
public class mainclass {
private static Scanner sc;
public static void main(String[] args) {
// TODO Auto-generated method stub
String s;
sc = new Scanner(System.in);
System.out.println("Enter a complete expresion");
s= sc.next();
stackop ob = new stackop();
System.out.println("YOUR PROVIDED input expression is :"+s);
//System.out.print(" Equivalent postfix notation is : ");
System.out.println("\n\n");
ob.postfix(s);
}
}
class stackop{
char stack1[]=new char[50];
int top;
void push(char ch)
{
top++;
stack1[top]=ch;
System.out.println(" element pushed is: "+ch);
System.out.println("----- current value of top is after push overs : "+top+" -------");
}
char pop(){
char ch;
ch= stack1[top];
//System.out.println("current value of top is : "+top);
System.out.println(" element popped is: "+ch);
--top;
System.out.println("----- current value of top is after pop overs : "+top+" -------");
return ch;
}
boolean isalpha(char a)
{
if((a>='a' && a<='z')||(a>=0 && a<=9))
return true;
else
return false;
}
boolean operator(char ch)
{
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
int prech(char ch){
switch(ch)
{
case '-': return 1;
//break;
case '+': return 1;
//break;
case '/': return 2;
//break;
case '*': return 2;
}
return 0;
}
void postfix(String str)
{
char otop=0;
char[] output = new char[str.length()+1];
for(int i=0 ; i<str.length();i++)
{
char ch=str.charAt(i);
System.out.println("==========value fetched is "+ch+" ===========");
if(ch=='(')
push(ch);
else if(isalpha(ch))
{
System.out.println("elemnt inserted in output list is :"+ch);
output[++otop]=ch;
}
else if(ch == ')' )
{
char temp=0;
System.out.println(" a close bracket is encounterd ");
while((temp=pop())!='(')
{
output[++otop]=temp;
System.out.println("elemnt inserted in output list is :"+temp);
}
}
else if(operator(ch))
{
if(prech(stack1[top])==0||(prech(stack1[top])<=prech(ch))||(prech(stack1[top])=='('))
push(ch);
}
else if(prech(stack1[top]) > prech(ch))
{
System.out.println(" hahah here i come");
output[++otop]=pop();
push(ch);
}
}
while(top>0)
{
output[++otop]=pop();
System.out.println("elemnt inserted in output list is :"+output[otop]);
}
System.out.println("\n\nOUTPUT OF EXPRESSION IS : " );
for(int j=0;j<str.length();j++)
{
System.out.print(""+output[j]);
}
}
}
In this chunk of code:
else if(operator(ch))
{
if(prech(stack1[top])==0||(prech(stack1[top])<=prech(ch))||(prech(stack1[top])=='('))
push(ch);
}
else if(prech(stack1[top]) > prech(ch))
The operator(ch) method returns true for your operators, which means control flow never reaches the second else if. What you probably want to do is move it inside the first else if, as shown below:
else if(operator(ch))
{
if(prech(stack1[top])==0||(prech(stack1[top])<=prech(ch))||(prech(stack1[top])=='('))
{
push(ch);
}
else if(prech(stack1[top]) > prech(ch)) { ... }
}
The title and the question do not have anything in common, also you should format your code. Nonetheless here's my answer to the question which you probably would've asked had you written an appropriate title.
Well actually 0 != '0' in programming, because '0' is translated to it's integer value which in ASCII is 48 and the comparison is between 0 and 48.
So your isalpha method should look like this:
boolean isalpha(char a)
{
if((a>='a' && a<='z')||(a>='0' && a<='9'))
return true;
else
return false;
}
Also, there are these neat little methods with which you don't need to check characters' ASCII code to compare them. I personally prefer this approachh as it is more simple and concise. It would look like this:
boolean isalpha(char a)
{
return Character.isDigit(a) || Character.isAlphabetic(a);
}

stack dealing with recognizng string in language, java program [closed]

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 9 years ago.
Improve this question
SO my program is about language L = {'w$w' : w is a possible empty string of characters other than $, w' = reverse(w)}
So when something like hod$doh is fed to the parameter of isINlanguage function it should return true, but my program just stops and hangs doesnt out put anything
import java.util.Stack;
public class Stacks
{
public static void main(String[] args){
boolean eval = isInLanguage("sod$dos");
System.out.println(eval);
}
static // astack.createStack();
boolean isInLanguage(String aString){
Stack<Character> aStack = new Stack<>();
int i = 0;
char ch = aString.charAt(i);
while (ch != '$') {
aStack.push(ch);
i++;
}
//Skip the $
++i;
// match the reverse of w
boolean inLanguage = true; // assume string is in language
while (inLanguage && i < aString.length()) {
char stackTop;
ch = aString.charAt(i);;
try {
stackTop = (char) aStack.pop();
if (stackTop == ch) {
i++;
} else {
// top of stack is not ch(Charecter do not match)
inLanguage = false; // reject string
}
} catch (StackException e) {
// aStack.poo() failed, astack is empty (first, half of Stirng
// is short than second half)
inLanguage = false;
}
}
if (inLanguage && aStack.isEmpty()) {
return true;
}
else{
return false;
}
}
}
You are not resetting the ch inside the while loop to the next character:
while (ch != '$') {
aStack.push(ch);
i++;
ch = aString.charAt(i); // Add this
}
Also, inside the try block, the cast is not necessary. The assignment:
stackTop = (char) aStack.pop();
... is better written as:
stackTop = aStack.pop();
BTW, you are really complicating your task, by using boolean variable, and try-catch blocks. Don't let the stack.pop() throw any exception. Rather, pop an element only if stack is not empty. Also, you can directly return as soon as you find the string doesn't matches the required language, so there is no need to boolean variable.
I would modify your method as:
static boolean isInLanguage(String aString){
Stack<Character> aStack = new Stack<>();
int i = 0;
char ch;
// This is simplified way to write your first while loop
// Read a character, move the index further, and test, all in single statement
while ((ch = aString.charAt(i++)) != '$') {
aStack.push(ch);
}
// Iterate till the stack is not empty
while (!aStack.isEmpty()) {
// Get next character in string, and pop an element from stack
// If they are not equal, return false
if (aString.charAt(i++) != aStack.pop()) {
return false;
}
}
// If we reach here, means stack is empty. Test if the index `i` has reached end of the string.
// If it reached the end of the string, return true, else return false (because there are still some characters to be processed).
return i == aString.length();
}
aString.charAt(i++) will get the character at index i, and increment i thereafter.

Categories

Resources