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).
Related
class Chotu
{
// Returns length of the longest subsequence of 1's
public static int ShortestSequence(String s) {
int count = 0;
int ans=s.length();
for(int i=0;i<s.length();i++)
{
if (s.charAt(i) == '1')
count++;
else
count = 0;
if(count < ans )
ans=count;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
String s =sc.next();
if(ShortestSequence(s) > 1)
System.out.println(ShortestSequence(s));
else
System.out.println(-1);
}
}
I'm making program to find shortest sequence of 1's in user input string. I had made program which gives me longest sequence need help.
Input : 11100011001
Output : 1
You can split the String and then use stream:
public static String shortestSequence(String str) {
return Arrays.stream(str.split("[^1]"))
.filter(Predicate.not(String::isBlank))
.sorted(Comparator.comparing(String::length))
.findFirst().orElse("");
}
public static String longestSequence(String str) {
return Arrays.stream(str.split("[^1]"))
.filter(Predicate.not(String::isBlank))
.sorted(Comparator.comparing(String::length).reversed())
.findFirst().orElse("");
}
Then:
String str = "11100011001";
System.out.println("Shortest: " + shortestSequence(str));
System.out.println("Longest: " + longestSequence(str));
Output:
Shortest: 1
Longest: 111
I tried to recursively reverse a string in Java, but I am getting just the last character as output.
I looked up online and most of the codes have modified the input string. I am trying to build the output from empty string to reversed string. Please tell me what is wrong in my program.
class reverseStringRecursion
{
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = " Hello I am my name.";
String output = "";
return recursiveHelper(strInput, 0, output);
}
public static String recursiveHelper(String strInput, int index, String output)
{
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
else
output+= recursiveHelper(strInput, index + 1, output) +"";
return output;
}
}
The above code is returning output '.' only and nothing else. PLease help.
Others have done a good job of explaining why your code doesn't work. For comparison, here's a working version with some comments:
public static void main(String args[])
{
System.out.println(reverse("Hello I am my name."));
}
public static String reverse(String text)
{
// Base case:
// If the string is empty, we're done.
if (text.length() == 0) {
return "";
} else {
// reverse("hello") = reverse("ello") + "h"
return reverse(text.substring(1)) + text.charAt(0);
}
}
Since String in Java are immuatable, passing it by parameter is useless on this case, so I removed it.
public class Main {
public static void main(String args[]) {
System.out.println(reverse());
}
public static String reverse() {
String strInput = " Hello I am my name.";
return recursiveHelper(strInput, 0);
}
public static String recursiveHelper(String strInput, int index) {
String output;
if(index == (strInput.length() - 1 )){
output = strInput.charAt(index) + "";
}else{
output = recursiveHelper(strInput, index + 1) + strInput.charAt(index);
}
return output;
}
}
Try it online!
Since strInput always contains the original String, the following condition makes sure your code only takes the last character of that String and ignore all the other characters:
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
To build the reversed String recursively, you have to append the last character of the String to the reverse of the sub-string of the first length()-1 characters.
This means that you don't need the 2nd and 3rd arguments of your method, and strInput should be passed a shorter String in each recursive call.
public static String reverse (String strInput)
{
if(strInput.length() <= 1)
return strInput;
else
return strInput.charAt(strInput.length()-1) + reverse (strInput.substring(0,strInput.length()-1));
}
I would change your function recursiveHelper() to only receive one argument (the String that you want to reverse). Using the substring method from Java you can do it like this:
public static String recursiveHelper(String strInput) {
if(strInput.length() == 1) {
return strInput;
}
else if(strInput == "") {
return "";
}
String subString1 = recursiveHelper(strInput.substring(0, strInput.length()/2)); // Here we copy the first half of the String to another String
String subString2 = recursiveHelper(strInput.substring(strInput.length()/2)); // Here we do the same, but with the second half of the original String
return susbString2 + subString1; // It is very important that you sum the two substrings in this order!
}
Modified your class:
public class ReverseStringRecursion {
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = "My Name is Jane Doe";
String output = "";
return recursiveHelper(strInput,0);
}
public static String recursiveHelper(String strInput, int index)
{
if(index == (strInput.length() - 1 ))
return "" + strInput.charAt(index) ;
else
return recursiveHelper(strInput,index+1) + strInput.charAt(index);
}
}
public class Main
{
public static void main(String[] args) {
String str1="abc";
String str2="";
for(int i=str1.length()-1;i>=0;i--)
{
str2=str2+Character.toString(str1.charAt(i));
}
System.out.println("After Reverse: "+str2);
}
}
1) Base case
if left>=right - do nothing
2) otherwise swap s[left] and s[right} and call helper(left+1, right-1)].
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char tmp = s[left];
s[left++] = s[right];
s[right--] = tmp;
}
}
}
public static int countWords(String str)
This method will count the number of words in str
For example, if str = "Hi there", the method would return 2.
I'm a beginner and not supposed to use pre-built programs. I know it probably uses a loop and I need to use .indexOf to find spaces? Something like my failed attempt at the bottom
public static int countWords(String str){
int count=0;
int len=str.length();
if(str.indexOf(" ")>=0){
for(int i=0; i<len; i++)
count=count+i;
}
return count;
You can just write
public static int countWords(String str){
if(str == null){
return 0; // or your wish to return something
}
str = str.trim();
return str.split("\\s+").length;
}
Where \\s+ will split the string even there are around spaces.
The current implementation is completely wrong:
If the string doesn't contain a space, it will not enter the if block, and incorrectly return 0, because that's the initial value of count and it was never changed
If the string contains a space, the loop does not what you want: it sums up the numbers from 0 to len, for example if len = 5, the result will be 0 + 1 + 2 + 3 + 4
There's nothing in the code to account for words. Note that counting the spaces would not be enough, for example consider the input: " Hello there :-) ". Notice the excessive spaces between words, and also at the start and end, and the non-word smiley.
This should be relatively robust:
int countWords(String text) {
String[] parts = text.trim().split("\\W+");
if (parts.length == 1 && parts[0].isEmpty()) {
return 0;
}
return parts.length;
}
The tedious if condition there is to handle some special cases:
empty string
string with only non-word characters
Unit tests:
#Test
public void simple() {
assertEquals(4, countWords("this is a test"));
}
#Test
public void empty() {
assertEquals(0, countWords(""));
}
#Test
public void only_non_words() {
assertEquals(0, countWords("##$#%"));
}
#Test
public void with_extra_spaces() {
assertEquals(4, countWords(" this is a test "));
}
#Test
public void with_non_words() {
assertEquals(4, countWords(" this is a test :-) "));
}
import java.util.Scanner;
public class CountWordsInString {
public static int countWords(String string) {
String[] strArray = string.split(" ");
int count = 0;
for (String s : strArray) {
if (!s.equals("")) {
count++;
}
}
return count;
}
public static void main(String args[]) {
System.out.println("Enter your string: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Total Words: " + countWords(str));
}
}
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
public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String text = bufReader.readLine();
shuffle("",text);
}
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
input = input.substring(i,1) + input.substring(0,i) + input.substring(i+1);
shuffle(dummy+input.substring(0,1),input.substring(1));
}
}
}
}
Am trying to print all the permutations of a string entered. And I really cannot guess where am going wrong because on paper I find that this executing. Where exactly am going wrong.
Try change your shuffle:
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
shuffle(dummy+input.charAt(i), input.substring(0, i) + input.substring(i+1, input.length()));
}
}
}
public class Permute {
public static void main(String[] args) throws IOException {
System.out.println("Enter a string");
BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
String text = bufReader.readLine();
shuffle("",text);
}
public static void shuffle(String dummy, String input){
if(input.length() <= 1)
System.out.println(dummy+input);
else{
for(int i=0; i <input.length();i++){
input = input.substring(i,i+1) + input.substring(0,i) + input.substring(i+1);
shuffle(dummy+input.substring(0,1),input.substring(1));
}
}
}
}
It should be input.substring(i,i+1) instead of input.substring(i,1). Because each time I need only 1 character to be constant, which is at the beginning of the string and others have to be jumbled.
The bug was I presumed the functionality of substring to be substring(beginIndex, length). But it is substring(beginIndex,endIndex).
#Oli: Thank you for the help.
Since this seems like a homework assignment I once did I will help you out here. You will need two loops, one inside the other.
for(int i;i<something;i++)
for(int j;j<somethingElse;j++)
This will enable you to generate the permutations that are required.
Replace two lines in the for loop with following:
String partString = input.substring(0, i) + input.substring(i + 1);
shuffle(dummy + input.charAt(i), partString);
Since this looks like your homework I will let you figure out. If not, will post explanation after a bit ( got to get back to my day job ;) )