Repeating a string - java

I am very new to programming and I have to write a method and program for the following; public static String repeat(String str, int n) that returns the string repeated n times. Example ("ho", 3) returns "hohoho" Here is my program so far:
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
System.out.println(repeat (str));//Having trouble with this line
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return ""//Having trouble with this line
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}
I made some changes to my code, but it still is not working
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String str = in.nextLine();
int n = in.nextInt();
System.out.println(repeat(str,n));
}
// **TEST PROGRAM**//
public static String repeat(String str, int n)
{
if (n <= 0)
{
return "";
}
else if (n % 2 == 0)
{
return repeat(str+str, n/2);
}
else
{
return str + repeat(str+str, n/2);
}
}
}

You've missed a semi colon on the line you're having trouble with, it should be return ""; and not return ""
Also, the line System.out.println(repeat (str)); should have 2 arguments because you're repeat definition is:
public static String repeat(String str, int n)
As a further note, an easier function might be
public static String repeat(String str, int n)
{
if (n == 0) return "";
String return_str = "";
for (int i = 0; i < n; i++)
{
return_str += str;
}
return return_str;
}

public static String repeat(String toRepeat, int n){
if(n==0){
return "";
}
return toRepeat+repeat(toRepeat,n-1);
}

2 things I noticed quickly: you forgot a semi-column and your call of "repeat" doesn't match the method signature (you forgot n)

You are not passing correct arguments while you calling the desired method.
Call as repeat (str,k) k - should be an integer

Related

Number of rotations required to make string

This is my code to count the number of rotations.
But IDK, What is the problem with it.
Can anyone explain and help me out.
Test Case: Input: david vidda
Output: 2
I tried to have brute force approach but, that wasn't working even.
Can anyone point out my mistake??
import java.util.*;
class solution{
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2)
{
int i;
int count =0;
for (i = 0; i < str1.length(); i++){
if(str1.equals(str2))
{
count++;
str1 = leftRotatebyOne(str1);
System.out.println(str1);
}
else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str)
{
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1));
str.setCharAt(i,temp);
return str;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String strr1= in.nextLine();
StringBuilder str1 = new StringBuilder(strr1);
String strr2 = in.nextLine();
StringBuilder str2 = new StringBuilder(strr2);
System.out.print(arrayLeftRotation(str1, str2));
}
}
Your method leftRotateByOne appears more complicated than necessary.
Try this:
public class Solution
{
public static int arrayLeftRotation(String str1,
String str2)
{
int nr_rotate;
int counter;
nr_rotate = 0;
for (counter = 0; counter < str1.length(); counter++)
{
if (str1.equals(str2))
return (nr_rotate);
else
{
str1 = leftRotateByOne(str1);
nr_rotate++;
System.out.println(str1);
}
}
// No possible solution
return (-1);
} // arrayLeftRotation
public static String leftRotateByOne(String str)
{
return (str.substring(1) + str.charAt(0));
}
public static void main(String[] args)
{
String str1 = "david";
String str2 = "vidda";
System.out.print(arrayLeftRotation(str1, str2));
}
} // class Solution
Another possible solution for arrayLeftRotation,
public static int arrayLeftRotation(String str1, String str2) {
StringBuilder builder = new StringBuilder(str1);
for (int i = 0; i < str1.length(); i++) {
builder.append(str1.charAt(i)).delete(0, 1);
if (str2.equals(builder.toString())) {
return i + 1;
}
}
return -1;
}
Note: this will return -1 if no matches found.
The trick is to append the input string to itself, then call String#indexOf. It will give you the index at which the doubled string contains the expected string, which is what you're looking for.
Example:
public static int numberOfRotations(String input, String expected) {
final String doubledInput = input + input;
return doubledInput.indexOf(expected);
}
If you really want to implement it yourself, you need to simplify your code to minimize the possibility of making mistakes.
public static String rotate(String input) {
return input.substring(1) + input.charAt(0);
}
public static int numberOfRotations(String input, String expected) {
// handle edge cases (null, empty, etc.) here
String rotatedInput = input;
int count = 0;
while (!rotatedInput.equals(expected) && count < input.length()) {
rotatedInput = rotate(rotatedInput);
count++;
}
return count == input.length() ? -1 : count;
}
I am just trying to point out where your error lies and fix it.
Your error lies here in your leftRotatebyOne:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(str.indexOf(str.charAt(i)+""),str.charAt(i+1)); // your error while shifting to the left;
What you are trying to do is shifting one position to the left, and you should just do it as:
for (i = 0; i < str.length()-1; i++)
str.setCharAt(i,str.charAt(i+1));
And then your method will work.
But I have to say Alex M has provided a cleaner solution to your problem. Perhaps you should have a try.
Your solution then can be (after the fix):
public class RotationCount {
public static int arrayLeftRotation(StringBuilder str1, StringBuilder str2) {
int i;
int count = 0;
for (i = 0; i < str1.length(); i++) {
if (!str1.toString().equals(str2.toString())) {
count++;
str1 = leftRotatebyOne(str1);
} else return count;
}
return count;
}
static StringBuilder leftRotatebyOne(StringBuilder str) {
int i;
char temp = str.charAt(0);
for (i = 0; i < str.length() - 1; i++) {
str.setCharAt(i, str.charAt(i + 1));
}
str.setCharAt(i, temp);
return str;
}
public static void main(String[] args) {
StringBuilder str1 = new StringBuilder("david");
StringBuilder str2 = new StringBuilder("vidda");
System.out.print(arrayLeftRotation(str1, str2));
}
}

counter for string search in another string

I want to search how many times a string appear in another string
It does not work correctly when i put an similar string at the end.
public class C3_Project3_WPr {
public static void main(String[] args) {
String strn1="AliAliAli";
String strn2="AliAliSinaAli";
String strn3="Ali";
int count1=StringCounter(strn1, strn3);
System.out.println(count1);
int count2=StringCounter(strn2, strn3);
System.out.println(count2);
}
//ُString in String Method
static int StringCounter(String str1, String str2){
int counter=0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for(int i= 0; i<str1.length(); i++){
if(str1.contains(str2)){
counter++;
str1= str1.substring(str2.length());
}
}
return counter;
}
}
Solution to your problem is here
public static void main(String[] args) {
String strn1 = "AliAliAliwewdwdweAli";
String strn2 = "AliAliSinaAliAlAli";
String strn3 = "Ali";
int count1 = StringCounter(strn1, strn3);
System.out.println(count1);
int count2 = StringCounter(strn2, strn3);
System.out.println(count2);
}
// ُString in String Method
static int StringCounter(String str1, String str2) {
int counter = 0;
if (str1.isEmpty() || str2.isEmpty()) {
return 0;
}
for (int i = str1.indexOf(str2); i >= 0; i = str1.indexOf(str2, i + str2.length())) {
counter++;
}
return counter;
}
}
When modifying str1 you only take in to account the length of the search string, but ignore the index in which it was found. Fixing this (e.g., by using indexOf), will fix your results too:
int index = str1.indexOf(str2);
while (index >= 0) {
counter++;
index = str1.indexOf(str2, index + str2.length());
}
Use recursive method: It's quick and easy way to solve your problem:
static int StringCounter(String str1, String str2){
return (str1.contains(str2)) ? 1 + StringCounter(str1.replaceFirst(str2, ""), str2) : 0;
}

How should I write this Java function recursively?

I'm trying to write the Java code below recursively:
public static int count(String word) {
int numValue = 0;
int length = word.length();
for(int i=0; i<length; i++){
String alpha = "abcdefghijklmnopqrstuvwxyz";
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
}
return numValue;
}
public static void main(String[] args) {
System.out.println(count("abc"));
}
The function returns the sum of the index of each letter in the input string parameter.
I'm attempting to write this same code recuersively, can anyone point out where I've gone wrong?
public static int count(int numValue, int i, String word) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
if( i >= word.length()){
return numValue;
}
else{
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
count(numValue, i=i+1, word);
}
return numValue;
}
public static void main(String[] args) {
System.out.println(count(0,0, "abc"));
}
A simpler way would be just shrink the string again and again.
public static int count(String word) {
if (word.isEmpty()) {
return 0;
}
final String alpha = "abcdefghijklmnopqrstuvwxyz";
return alpha.indexOf(word.charAt(0)) + count(word.substring(1));
}
To change this function to be recursive, you would ideally use divide and conquer approach which is rather easy to implement. I will present it in a simple and verbose way so that you can see the steps clearly.
public static int count(String word) {
int numValue = 0;
int length = word.length();
if(length > 1)
{
String substring1 = word.substring(0, length/2);
String substring2 = word.subtring(length/2 + 1, length);
numValue += count(substring1);
numValue += count(substring2);
return numValue;
}
else
{
String alpha = "abcdefghijklmnopqrstuvwxyz";
return alpha.indexOf(word) + 1;
}
}
public static void main(String[] args) {
System.out.println(count("abc"));
}
I suppose you are doing this as an exercise to teach yourself recursiveness - if not, you may want to think whether it is not better for you to just use the iterative approach instead of recursiveness.
The variable numValue is of type int. So it doesnt get changed in the calling method, wenn you pass it to another method and change it in there. This means, the line count(numValue, i=i+1, word); basically does nothing.
You can correct the method by returning the result of the recursive call (Since you return in the if, else is not needed):
public static int count(int numValue, int i, String word) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
if( i >= word.length()){
return numValue;
}
String letter = (word.substring(0 + i,1 + i));
numValue = numValue + alpha.indexOf(letter) + 1;
return count(numValue, i=i+1, word);
}
This is the reason, why your function does not work properly. The answer provided by timrau is a nicer solution for the recursion.

How can i make the code print backwards recursively?

Here's my code.
I am trying to make the String entered print out backwards, but every time I run it the code doesn't print out anything when it's called to print in reverse.
package Pali;
import java.util.Scanner;
/**
* Created by alexa on 11/4/2016.
*/
public class Palindromes {
public static void main(String[] args)
{
String msg;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
msg = scan.nextLine();
System.out.print("\nThe string backwards: ");
printBackwards(msg);
System.out.println();
}
public static String printBackwards(String s)
{
if (s.length() == 0)
return s;
return printBackwards(s.substring(1)) + s.charAt(0);
}
}
printBackwards actually just returns a String, but does nothing else. To print that returned String you would have pass it to the println method.
public static void main(String[] args)
{
String msg;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
msg = scan.nextLine();
System.out.print("\nThe string backwards: ");
String reversed = printBackwards(msg);
System.out.println(reversed);
}
Alternatively, you can let printBackwards print the String and leave the main method as it was:
public static String printBackwards(String s)
{
if (s.length() == 0)
{
System.out.println(s);
return s;
}
return printBackwards(s.substring(1)) + s.charAt(0);
}
Well you forgot to print letters
public static void printBackwards(String s)
{
if (s.length() == 0) return ;
printBackwards(s.substring(1));
System.out.print(s.charAt(0));
}
DEMO
Iteratively:
static String printBackwards(String s) {
StringBuilder sb = new StringBuilder();
for(int i = s.length() - 1; i >= 0; --i)
sb.append(s.charAt(i));
return sb.toString();
}
Recursively:
static String printBackwards(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
}
Your code calls printBackwards, but immediately discards the output.
Try changing line 6 of main() to System.out.print(printBackwards(msg));
Given that, I would also think about changing the method name to something like reverseString(String).

Converting a number to binary java code

I am writing a code to convert a number to binary representation.Here's my code.It doesn't give the correct answer but I can't figure out where I am making the mistake.If someone could point out where my mistake and how to correct it I would be grateful.
public class ConvertBinary{
public static String convertBinary(int n){
String s="";
while(n>0){
s+=(n%2);
n=n/2;
}
int len=s.length();
String[] binary=s.split("");
String[] binaryCopy=new String[s.length()];
for(int i=0;i<len;i++){
binaryCopy[i]=binary[len-i-1];
s+=binaryCopy[i];
}
return s;
}
public static void main (String args[]){
System.out.println(convertBinary(19));
}
}
Apart from all these answers the problem with your code was that you are not clearing the string before reversing it. So before the for loop just put s = "" and you code should work fine.. :)
Based on comment
public class ConvertBinary {
public static String convertBinary(int n) {
String s = "";
while (n > 0) {
s += (n % 2);
n = n / 2;
}
int len = s.length();
String[] binary = s.split("");
String[] binaryCopy = new String[s.length()];
s = "";
for (int i = 0; i < len; i++) {
binaryCopy[i] = binary[len - i - 1];
s += binaryCopy[i];
}
return s;
}
public static void main(String args[]) {
int num = 4;
System.out.println(convertBinary(num));
System.out.println(Integer.toBinaryString(num));
}
}
public static String convertBinary(int n){
String s="";
while(n>0){
s+=(n%2);
n=n/2;
}
return (new StringBuffer(s).reverse().toString());
}
If you're looking for error in your implementation, you'd rather put:
s = (n % 2) + s;
isntead of
s+=(n%2);
so the code'll be
// n should be positive
public static String convertBinary(int n){
if (n == 0)
return "0";
String s = "";
// for is more compact than while here
for (; n > 0; n /= 2)
s = (n % 2) + s;
return s;
}
however in real life
Integer.toString(n, 2);
is much more convenient
Use Java standard library: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString%28int,%20int%29
public class ConvertBinary{
public static String convertBinary(int n){
return Integer.toString(n, 2);
}
public static void main (String args[]){
System.out.println(ConveryBinary.convertBinary(19));
}
}
EDIT: As #Holger says, there's also a toBinaryString: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString%28int%29
public static String convertBinary(int n){
return Integer.toBinaryString(n);
}

Categories

Resources