I've been working with a program recently in java which compiles successfully but during execution,after i enter the string, nothing gets displayed, allowing me to type anything on the execution page.The program goes like this:- The user enters a string with a couple of missing letters represented by '.'(a full stop).
The program should fill in those full stops to make a smallest (lexicographically) palindrome word. If this is not possible....display not possible to make a palindrome. Please tell me if i've gone wrong anywhere. Thank you :)
import java.io.*;
public class JavaApplication {
static String s;
//main method
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string with '.' as their missing characters:");
s=br.readLine();
int len=s.length();
String result;
if(len%2==0){
result=even();
}
else
result=odd();
System.out.println(result);
}
//Function to handle odd no. of characters
static String odd(){
int len=s.length();
int mid=(len-1)/2;
for(int i=1;i<=mid;i++){
if(s.charAt(mid-i)=='.'||s.charAt(mid+i)=='.'){
if(s.charAt(mid)=='.'){
s=s.substring(0,mid)+'a'+s.substring(mid+1);
}
if(s.charAt(mid-i)=='.'&&s.charAt(mid+i)=='.'){
s=s.substring(0,(mid-i))+'a'+s.substring((mid-i)+1,mid)+s.charAt(mid)+s.substring(mid+1,mid+i)+'a'+s.substring((mid+i)+1);
}
if(s.charAt(mid-i)=='.'){
s=s.substring(0,mid-i)+s.charAt(mid+i)+s.substring((mid-i)+1);
}
if(s.charAt(mid+i)=='.'){
s=s.substring(0,(mid+1))+s.charAt(mid-i)+s.substring((mid+1)+1);
}
}
}
String result=checkPalindrome();
return result;
}
//Function to handle even no. of characters
static String even(){
int len=s.length();
int mid2=len/2,mid1=mid2-1;
for(int i=0;i<mid2;i++){
if(s.charAt(mid1-i)=='.'||s.charAt(mid2+i)=='.'){
if(s.charAt(mid1-i)=='.'&&s.charAt(mid2+i)=='.'){
s=s.substring(0,mid1-i)+'a'+s.substring((mid1-i)+1,mid2+i)+'a'+s.substring((mid2+i)+1);
}
if(s.charAt(mid1-i)=='.'){
s=s.substring(0,mid1-i)+s.charAt(mid2+i)+s.substring((mid1-i)+1);
}
if(s.charAt(mid2+i)=='.'){
s=s.substring(0,mid2+i)+s.charAt(mid1-i)+s.substring((mid2+i)+1);
}
}
}
String result=checkPalindrome();
return result;
}
//Check if s is palindrome
static String checkPalindrome(){
String s1=s;
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
s1=ch+s1;
}
if(s1.equals(s))
return s1;
else{
s1="cannot form any palindrome";
return s1;
}
}
}
Related
Suppose there is a string s=abcd
I want the 5th string consisting of a,b,c,d, which is adbc.
But I also get all the answers beyond it which I don't need.
So how can I stop this method after its 5th execution?
import java.util.Arrays;
import java.util.Scanner;
class Test{
long times;
int n=1;
public static void main(String[] args) {
Test tm=new Test();
Scanner in=new Scanner(System.in);
int t=Integer.parseInt(in.nextLine());
while(t!=0){
String s=in.nextLine();
char ch[]=s.toCharArray();
Arrays.sort(ch);
String sort=String.valueOf(ch);
String ans;
long n=Long.parseLong(in.nextLine());
tm.times=n;
tm.permu("",sort);
t--;
}
}
private void permu(String prefix,String str) {
int len=str.length();
if(len==0){
if(n==times){
System.out.println(prefix);
}
else{
n++;
}
}
else{
for(int i=0;i<len;i++){
permu(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, len));
}
}
}
}
Secondly is there any site where I can read about permutation, combination and probability for calculating and finding the permutation, combination and probability... For coding thing not for mathematical thing..i.e I know how to solve mathematically but I can't code it.. Unable to write logic for it.
You don't change n after running the check and printing a result in your recursion. That's why you print everything after adbc.
If you use this code when checking:
if (n == times) {
System.out.println(prefix);
n = -1;
} else {
if (n > -1)
n++;
}
then you only get n == times to be true once, and that's when the prefix is adbc.
Example test for the solution:
If you want to stop a method that has no return value (has void in its return type in the method signature), then calling return; will exit the method... But it isn't needed here.
import java.io.*;
public class runner{
//Translates from infix to postfix
//Evaluates the postfix expression
public static tokenlist xform(String input){
//operand get pushed automatically onto linked list
//operator we will see;
tokenlist postfix=new tokenlist();
stack stack=new stack();
int c=0;
while(input.substring(c,c) != null){
if(prec.isoper(input.substring(c,c))==false){
postfix.push(input.substring(c,c),false);
}else{
if(stack.inspect()==null){
stack.push(input.substring(c,c));
}else{
if(prec.inprec(input.substring(c,c))>prec.stackprec(stack.inspect())){
while(prec.inprec(input.substring(c,c))>prec.stackprec(stack.inspect())){
String s=stack.pop();
postfix.push(s,true);
}
}else{
stack.push(input.substring(c,c));
}
}
}
c++;
}
return postfix;
}
public static double eval(tokenlist postfix){
astack numbers=new astack();
Double ans=0.0;
numbers.push(Double.parseDouble(postfix.getTing()));
while(numbers.isEmpty() != true){
if(postfix.getFunc()== false){
numbers.push(Double.parseDouble(postfix.getTing()));
}else{
double c=0.0;
double a=numbers.pop();
double b=numbers.pop();
if(postfix.getTing()=="+"){
c=a+b;
numbers.push(c);
}
if(postfix.getTing()=="-"){
c=b-a;
numbers.push(c);
}
if(postfix.getTing()=="*"){
c=a*b;
numbers.push(c);
}
if(postfix.getTing()=="/"){
c=b/a;
numbers.push(c);
}
if(postfix.getTing()=="^"){
double store;
double rep=0.0;
while(rep<=a){
c=b*b;
store=c;
rep=rep+1.0;
}
numbers.push(c);
}
if(postfix.getTing()=="\\"){
c=Math.abs(b-a);
numbers.push(c);
}
}
ans=numbers.pop();
}
return ans;
}
public static void main(String[] args){
try{
tokenlist postfix=xform(args[0]);
postfix.printlist();
double d=eval(postfix);
System.out.println(d);
}catch(Exception e){System.out.print(e);}
}
}
Regardless of what number is within args[#] in the main, I keep geting the above exception and String index out of range: Whatever number is in args[#] in the main. I already checked in the xform and it takes in the input as a string and the substring starts at 0. Still it doesn't work. I f anyone could have an explanation or tips they would be greatly appreciated.
You're code contains the line while(input.substring(c,c) != null)
This is basically an endless loop until c is higher that the length of your string which causes the exception.
Try to change it to while(c < input.length()) and you should be good to go.
Furthermore I hope you are aware of the fact that substring(c,c) will always return an empty string.
If you want a single character either use .charAt(c) or .substring(c, c+1)
public class RecursionPracticeProgram {
KeyboardReader reader = new KeyboardReader();
public String backString(String s){
s = reader.readLine("String: ");
if(s.length()==0)
return s;
System.out.println(backString(s.substring(1)) + s.charAt(0));
return backString(s.substring(1)) + s.charAt(0);
}
public void run(){
backString("Fox");
}
I am doing some recursion work but am having trouble printing it out. I think I have the code correct for reversing a string but when I go to run the program it just builds and doesn't actually print anything out. How do I print it out properly?
You need to make sure to only read once and you call your method at all.
Just do it like this:
public class RecursionPracticeProgram {
public void run() {
String input = reader.readLine("String: ");
KeyboardReader reader = new KeyboardReader();
System.out.println(reader.backstring(input));
}
public String backString(String s){
if(s.length()==0)
return s;
System.out.println(backString(s.substring(1)) + s.charAt(0));
return backString(s.substring(1)) + s.charAt(0);
}
}
I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";
So basically I'm doing a java tutorial but in order to follow along I need to make a class file. Everything was already given to me but it gives me an error. The error is: Delete else statement or something along those lines. But when I delete it it tells me to put another else statement there.
The code is : Is this a problem with eclipse or is there something wrong with the code?
import java.io.*;
import java.text.*;
public class In {
static InputStreamReader r = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(r);
// Read a String from the standard system input
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
return "";
}
}
// Read a number as a String from the standard system input
// and return the number
public static Number getNumber() {
String numberString = getString();
try {
numberString = numberString.trim().toUpperCase();
return NumberFormat.getInstance().parse(numberString);
} catch (Exception e)
{
// if any exception occurs, just return zero
return new Integer(0);
}
}
// Read an int from the standard system input
public static int getInt() {
return getNumber().intValue();
}
// Read a long from the standard system input
public static long getLong() {
return getNumber().longValue();
}
// Read a float from the standard system input
public static float getFloat() {
return getNumber().floatValue();
}
// Read a double from the standard system input
public static double getDouble() {
return getNumber().doubleValue();
}
// Read a char from the standard system input
public static char getChar() {
String s = getString();
if (s.length() >= 1)
return s.charAt(0);
else
return’\ n’;
}
}
What is actually causing the error here is that whatever messed up marks you have around \n are not apostrophes... I have no idea what they are. After rewriting the code exactly as you did, except with apostrophes (plus using curly braces in the if and else statements because I prefer it that way), there were no errors:
public static char getChar ()
{
String s = getString();
if (s.length() >= 1){
return s.charAt(0);
}else{
return '\n';
}
}
Please, in the future, make sure to use correct indentations in your questions to make it much easier for us to read.