Reputation: 136
Given question is: A string can contain only a, b or c. There cannot be 2 consecutive same character. First and last character cannot be same. Now given a string with ‘a’, ‘b’, ‘c’ or ‘?’. We need to find the string replacing ‘?’ that satisfy the above conditions. For multiple answer display lexicographically smallest string. For no answer possible display “Not Possible”.
import java.util.*;
class Replace {
public static void main(String args[]) {
char[] arr = { 'a', 'b', 'c' };
char Pre, Suc;
Scanner in = new Scanner(System.in);
String str = new String();
String str2 = new String();
System.out.println("Enter the String");
while (in.hasNextLine()) {
str = in.nextLine();
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '?') {
Pre = str.charAt(i - 1);
Suc = str.charAt(i + 1);
for (int j = 0; j < 3; i++) {
while (arr[j] != Pre && arr[j] != Suc) {
str2 = str.substring(0, i) + arr[j]
+ str.substring(i + 1, (str.length() - 1));
}
}
}
}
System.out.println(str2);
}
}
The code is compiling without any errors. I still have to add a couple of things to the code as per question but I was trying to check if the code was correct so far but I am not getting any Output. Any tips/suggestions to improve the code is welcome.
Upvotes: 0
Views: 135
Reputation: 1
You need a condition to break the first while loop. When the user insert the input string he press enter, so the Scanner get the second input as an empty string. You could check the empty string and exit from the while loop.
import java.util.*;
class Replace
{
public static void main(String[] args)
{
char[] arr = {'a','b','c'};
char Pre,Suc;
Scanner in = new Scanner(System.in);
String str = new String();
String str2 = new String();
System.out.println("Enter the String");
while(in.hasNextLine())
{
if(str.isEmpty()) break;
str = in.nextLine();
}
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='?')
{
Pre = str.charAt(i-1);
Suc = str.charAt(i+1);
for(int j=0;j<3;i++)
{
while(arr[j]!=Pre && arr[j]!=Suc)
{
str2 = str.substring(0,i)+arr[j]+str.substring(i+1,(str.length()-1));
}
}
}
}
System.out.println(str2);
}
}
Upvotes: 0
Reputation: 3608
Pre = str.charAt(i-1);
and Suc = str.charAt(i+1);
is problematic when "?" is the first/ last letter. It will cause then a java.lang.StringIndexOutOfBoundsException
while
-loop used for reading the input, hence System.out.println(str2);
is never reached.Upvotes: 2
Reputation: 1120
The problem is the program gets stuck in your while(in.hasNextLine()) { str = in.nextLine(); }
loop. There is no exit condition. hasNextLine
will block until a new line is entered. As per the Javadoc:
This method may block while waiting for input.
Upvotes: 1