How to print out a recursion method? - java

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);
}
}

Related

Making Palindrome(if possible) by filling missing characters

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;
}
}
}

Validating input string with java

First off, I will admit that this is an assignment of mine. however, I am at my wits end. I tried need to validate that the user input a proper expression (ie: "7 + 5;") and I managed to do it with split methods but I was told that I can't do that. I'm sure there is a simple solution to the problem but I am not seeing it.
The code is rather lengthy so I won't post it but if I will if needed.
Thanks!
Edit to answer questions: I am writing in jGrasp, so they can do whatever is on the keyboard. I was told to "Find a creative way to use substrings" which I don't know what that means. The expression needs to be Number Space operand Space number semicolon
here is what I have for the validation... I am using arrays for each character in the expression
public static boolean validFormat(String expr)
{
String tokens[] = expr.substring()
if (tokens.length == 3)
{
if (tokens[0].equals(""))
{
return false;
}
if (tokens[1].equals(""))
{
return false;
}
if (tokens[2].length < 2)
{
return false;
}
else
{
if (tokens[2].endwith(";"));
{
return false;
}
else
{
return true;
}
}
}
return false;
}
I get an error with calling the substring as well as an "else without if" error
First, you should limits the input to 6 characters using an if statement. Then use the CharAt() method to return each character to check the condition.
I was told to "Find a creative way to use substrings".
As told, try using String.substring() for the same.
public class Demo {
public static void main (String[] args) {
String exp = "7 + 5;";
System.out.printf("%s\t%b%n", exp, validate(exp));
exp = "4 + d;";
System.out.printf("%s\t%b%n", exp, validate(exp));
}
public static boolean validate(String exp) {
String n1 = exp.substring(0,1);//operand
String n2 = exp.substring(4,5);//operand
String co = exp.substring(5);//semicolon
String s1 = exp.substring(1,2);//space
String s2 = exp.substring(3,4);//space
String op = exp.substring(2,3);//operator
return num(n1) && num(n2) && semi(co) && space(s1) && space(s2) && opt(op);
}
public static boolean num(String n) {
return "0123456789".contains(n);
}
public static boolean semi(String s) {
return ";".equals(s);
}
public static boolean space(String s) {
return " ".equals(s);
}
public static boolean opt(String s) {
return "-+*%/^".contains(s);
}
}
This solution uses RegExp:
public class Demo {
public static void main (String[] args) {
String exp = "7 + 5;";
System.out.printf("%s\t%b%n", exp, validate(exp));
exp = "4 + d;";
System.out.printf("%s\t%b%n", exp, validate(exp));
}
public static boolean validate(String exp) {
return exp.matches("\\d\\s(\\+|\\-|\\*|\\/|\\^|\\%)\\s\\d\\;");
}
}

Java Error; array required, but java.lang.String found

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...";

Error in my Word program in Java

This is my code and it compiles fine but when I try to create a string it says
Error: cannot find symbol - variable racer
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
}
public boolean isPalindrome() {
if(original.equals(reverse()))
return true;
else
return false;
}
}
The stated problem is not in the code posted - my guess is irrelephant's comment is correct, ie change new Word(racer) --> new Word("racer").
But I offer this to eliminate any chance of any errors in your code by basically eliminating your code:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public boolean isPalindrome()
return new StringBuilder(original).reverse().toString().equals(original);
}
}
or if you must expose a reverse() method:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
return new StringBuilder(original).reverse().toString();
}
public boolean isPalindrome()
return reverse().equals(original);
}
}
I don't see the variable racer anywhere, but since you're using reverse inside a method, I'd recommend making it
Most likely, racer was never defined
Either that or the method was called w/o quotes
isPalindrome(racer)//note the lack of quotes
change reverse() to this
private() String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;

My Java Program won't Compile

As I just stated above this program won't compile. In my IDE, TextPad, it gives me 2 errors in the createArray method. It says that both a right bracket and semicolon are expected in my return statement when I indeed have them there. Could someone help me out here?
public class Driver
{
private static int size;
private static String somePromptMessage;
private static boolean validInput;
private static String userData;
public static void main(String[] args) throws IOException
{
validInput = false;
BufferedReader keyboard;
keyboard = new BufferedReader(new InputStreamReader(System.in));
int result;
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
{
return result;
}
}
public static void print(int[]x)
{
System.out.println("The array contains" + size + "elements");
for(int i = 0; i<x.length; i++)
{
System.out.println(x[i]);
}
}
private static int[] createArray(int size)
{
return int[size];
}
You're missing the enclosing } for the class, but I'll assume that one is a copy-paste issue.
The actual problem I see is that you want
return new int[size];
instead of
return int[size];
in your createArray function.
I see an extra simi-colon here:
while(!validInput);
{
return result;
}
Update: It was brought to my attention that this is actually a do while so why the extra braces around the return statement?
remove braces after while across return result; as it is do-while:
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
return result;

Categories