I am trying to create a program that takes int t and String s from the user. String s will be split at the spaces and put into a String[] Strings. When t=1, the main method prints Strings, reverses its elements using recursion in method reverse that takes two ints (the indices of the ends) and a String array, then print the reversed String array. The code below compiled with no problems, but I got an ArrayIndexOutOfBounds error right when I hit enter inputting 1 for t. The error references lines 11 and 34, but I'm scratching my head because I can't see anything wrong.
import java.util.Scanner;
public class Recursion
{
public static String[] reverse(int m, int n, String[] str)
{
String[] p = new String[str.length];
if (m == n) return str;
else if (m > n) return str;
else
{
str[m] = p[n];
str[n] = p[m];
return reverse(m+1, n-1, str);
}
}
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
System.out.print("t = ");
int t = enter.nextInt();
System.out.print("s = ");
String str = enter.nextLine();
String[] Strings = str.split(" ");
int k = Strings.length;
if (t == 1)
{
for (String s : Strings)
System.out.println(s);
System.out.println("The reversal is");
reverse(k-k, k, Strings);
for (String s : Strings)
System.out.println(s);
}
}
}
Array in java start from 0 to length -1
see Arrays for more details.
so passing k will throw ArrayIndexOutOfBounds use below code
reverse(0, k-1, Strings);
Related
This assignment ask to implement printWordRun so that it prints whatever word run it can find starting from the beginning of the input list words. The word run should be printed in reverse order, with each word on a separate line. PrintWordRun is a method which takes a parameter called words which is an ArrayList<String>. The word run is a series of words in the input list, where each word is longer in length than the previous. The word run ends once we either encounter the end of the list, or we encounter a word whose length is equal to or shorter than the previous word.
The array is:
I
am
cat
with
happy
dog
sitting
the result should be:
happy
with
cat
am
I
To get full credit for this assignment, I have to use a stack to print it as I have done, but I cannot get the word "happy" into the stack. My output is:
I
am
cat
with
public class Program {
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for(int i = 1; i < words.size(); i++) {
String str1 = words.get(i-1);
String str2 = words.get(i);
if(str2.length() < str1.length()) {
break;
}
if(str1.length() < str2.length()){
wordRun.push(str1);
}
System.out.println(wordRun);
}
}
public static void main(String[] args) {
Program program = new Program();
program.testPrintWordRun();
}
private void testPrintWordRun() {
ArrayList<String> words = new ArrayList<>();
words.add("I");
words.add("am");
words.add("cat");
words.add("with");
words.add("happy");
words.add("dog");
words.add("sitting");
System.out.println("Testing printWordRun...");
printWordRun(words);
System.out.println();
}
}
Here is one way to construct the printWordRun function:
Stack<String> wordRun = new Stack<>();
int maxLength = 0;
for(String s : words) {
if(s.length() > maxLength ) {
maxLength = s.length();
wordRun.add(s);
} else
break;
}
while(!wordRun.isEmpty())
System.out.println(wordRun.pop());
Just store a value of the current, maximum length and use this to compare your current string.
Output:
Testing printWordRun...
happy
with
cat
am
I
Start by adding the word to the stack with add(int index, E element) to insert the last item as first, and break the loop if the condition doesn't match afterwards.
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for (int i = 1; i < words.size(); i++) {
String str1 = words.get(i);
String str2 = words.get(i - 1);
wordRun.add(0, str2);
if(str2.length() >= str1.length()) {
break;
}
}
System.out.println(wordRun); // [happy, with, cat, am, I]
}
Today I am trying to convert String to reverse String e.g(Cat Is Running into Running Is Cat) word by word not Character
public class ReverseString_ {
public static void reverse(String str) {
String[] a = str.split(" ");
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i] + " ");
}
}
public static void main(String[] args) {
reverse("Cat Is Running");
}
}
The following output is shown:
Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)
I am trying to convert String into reverse String same as above but through Recursion method but it seems too confusing. and display more errors. Can someone please help me understanding it. Many thanks
public static String reverse_recursion(String str) {
if (str == null)
return null;
else {
String Arry[] = str.split(" ");
int n = Arry.length - 1;
System.out.println(Arry[n] + "");
return reverse_recursion(Arry[n - 1]);
}
}
public static void main(String[] args) {
reverse_recursion("Cat Is Running");
}
This code show following output:
Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
This code do not print (0) index why? can someone help me to solve this error please
This solution might be helpful. The comments explain the code pretty much.
public static String reverse_recursion(String str) {
String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings
if (arry.length > 1) { //If there is more than 1 word in arry
//Return the reverse of the rest of the str (arry[1])
//and concatenate together with the first word (arry[0])
return reverse_recursion(arry[1]) + " " + arry[0];
}
return arry[0]; //If less than or equal to 1 word, just return that word
}
This should work:
public static String reverse(String s) {
int idx = s.indexOf(" ");
if (idx < 0) {
// no space char found, thus, s is just a single word, so return just s itself
return s;
} else {
// return at first the recursively reversed rest, followed by a space char and the first extracted word
return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
}
}
public static void main(String[] args) {
System.out.println(reverse("Cat Is Running"));
}
You are sending the last element of the Array next time instead of the String without the previously printed String.
Replace your return statement with this it should work.
return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));
I have a string which i have to split into substrings of equal length if possible. I have found this solution which will only work if the string length is a multiple of 4.
String myString = "abcdefghijklm";
String[] split = myString.split("(?<=\\G....)");
This will produce:
[abcd, efgh, ijkl, m]
What i need is to split "from the end of the string". My desired output should look like :
[a, bcde, fghi, jklm]
How do i achieve this?
This ought to do it:
String[] split = myString.split("(?=(....)+$)");
// or
String[] split = myString.split("(?=(.{4})+$)");
What it does is this: split on the empty string only if that empty string has a multiple of 4 chars ahead of it until the end-of-input is reached.
Of course, this has a bad runtime (O(n^2)). You can get a linear running time algorithm by simply splitting it yourself.
As mentioned by #anubhava:
(?!^)(?=(?:.{4})+$) to avoid empty results if string length is in multiples of 4
Regex are really unnecessary for this. I also don't think this is a good problem for recursion. The following is an O(n) solution.
public static String[] splitIt(String input, int splitLength){
int inputLength = input.length();
ArrayList<String> arrayList = new ArrayList<>();
int i = inputLength;
while(i > 0){
int beginIndex = i - splitLength > 0 ? i - splitLength : 0;
arrayList.add(0, input.substring(beginIndex, i));
i -= splitLength;
}
return arrayList.toArray(new String[0]);
}
No need to use a regular expression. Instead, you can recursively build a list of head strings and return the tail.
import java.util.*;
public class StringChunker {
public static void main(String[] args) {
String str = "abcdefghijklm";
System.out.println(Arrays.toString(chunk(str, 4))); // [abcd, efgh, ijkl, m]
System.out.println(Arrays.toString(chunk(str, 4, true))); // [a, bcde, fghi, jklm]
}
public static String[] chunk(String str, int size) throws IllegalArgumentException {
return chunk(str, size, false);
}
public static String[] chunk(String str, int size, boolean reverse) throws IllegalArgumentException {
return chunk(str, size, reverse, new ArrayList<String>());
}
private static String[] chunk(String str, int size, boolean reverse, List<String> chunks) throws IllegalArgumentException {
if (size < 1) {
throw new IllegalArgumentException("size must be greater than 0");
}
if (str.length() < size) {
if (reverse) {
chunks.add(0, str); // Reverse adds to the front of the list
} else {
chunks.add(str); // Add to the end of the list
}
return chunks.toArray(new String[chunks.size()]); // Convert to an array
} else {
String head, tail;
if (reverse) {
head = str.substring(str.length() - size, str.length());
tail = str.substring(0, str.length() - size);
chunks.add(0, head);
} else {
head = str.substring(0, size);
tail = str.substring(size);
chunks.add(head);
}
return chunk(tail, size, reverse, chunks);
}
}
}
I'm currently doing an activity that requires me to write this:
Write a definition for a static method stringHeads that inputs an array of ints p and a String s. For each of the ints n in p, the method builds the substring consisting of the first n characters in s (or the whole of s, if n is greater than the length of s). The method returns the array of these substrings.
My code is currently something like this:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p)
e = b - 1
for (int de = 0; rad.length > de; de++)
rad[de] = s.substring(0,e);
for (String str : rad)
return str;
}
//Just ignore the rest
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon"
stringHeads(a,b)
The output should be "Rado" , "Ra", "Rad", "Ra", "".
The error that I'm currently getting is that String cannot be converted to String[].
Basically my question is how to fix this error and if a better code can be written.
Three things:
e would be constant if you enter the second loop.
e could be larger than s.length() - you didn't handle this case.
You return a String instead of a String[]
And please always use braces if you use loops, even if the loop only contains one statement. It is much more readable and can avoid errors.
I think you will have to rethink your whole function. Don't know if it would be helpful to write the function for you.
Hints:
Write only one loop!
String[] rad = new String[p.length];
for (int i=0; i < p.length; i++) {
if (s.length() < ??) {
rad[i] = s.substring(0,??);
} else {
??
}
}
return rad;
I hope this will help you to get the answer yourself.
See my code below hope it helps:-
I provided the comments instead of explaining it in paragraph.
As for your error, you are returning String from method but expected is an array of String.
public static void main(String[] args){
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] output=stringHeads(a,b);
for(String s:output){
System.out.println(s);
}
}
Your method can be like below:
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
//Iterate over integer array
for(int index=0; index<p.length; index++){
//Extracting the integer value from array one by one
e=p[index];
//If integer value is greater than String length
if(e>s.length()){
//Put the entire String in String array
rad[index]=s;
}else{
//Put the Substring value with range 0 to e i.e. integer value
rad[index]=s.substring(0,e);
}
}
return rad;
}
You could simplify you code by just using a single iteration with an alternative variable.
public static void main (String[] args) throws java.lang.Exception
{
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] result = stringHeads(a,b);
for(String x : result) System.out.println(x);
//Or you can write a separate display method instead.
}
public static String[] stringHeads(int[] p, String s)
{
String[] rad = new String[p.length];
//Use this variable for array allocation/iteration.
int i=0;
//Simply iterate using this for-each loop.
// This takes care of array allocation/ substring creation.
for (int x : p)
rad[i++] = s.substring(0,x);
return rad;
}
Please check the code below
public static String[] stringHeads(int[] intArray, String str) {
String[] result = new String[intArray.length];
int count=0;
for (int intValue : intArray)
{
result[count] = str.substring(0,intValue);
count++;
}
return result;
} //Just ignore the rest
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0 };
String b = "Radon";
String[] strArray=stringHeads(a,b);
int count=0;
for(String str:strArray)
System.out.println(++count+"" +str);
}
Change your method like this
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
rad[e] = s.substring(0, b);
e++;
}
return rad;
}
For use this method
public static void main(String[] args) {
int[] a = {4, 2, 3, 2, 0};
String b = "Radon";
String[] stringHeads = stringHeads(a, b);
for (String stringHead : stringHeads) {
System.out.println(stringHead);
}
}
Output is
Rado
Ra
Rad
Ra
There is no need for the for loop that iterates through the integer array p
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
for (int de = 0; de < p.length; de++){
if (p[de] < s.length())
rad[de] = s.substring(0,p[de]);
else
rad[de]=s;
}
return rad;
}
public static String[] stringHeads(int[] p, String s) {
String[] rad = new String[p.length];
int e = 0;
for (int b : p) {
if(b<=s.length()){
rad[e] = s.substring(0, b);
}
e++;
}
return rad;
}
I want to split a String into n number of characters.
Consider input to be "Example-for-my-Question". Now if I want to split into n=3 characters, output should be "Exa, mpl, e-f, or-, my-, Que, sti, on" and suppose n=4, output should be "Exam, ple-, for-, my-Q, uest, ion" How can you modify the program below without using POSIX.
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String; ");
String inputString = in.nextLine();
System.out.println("How many characters do you want to split into ?");
int n = in.nextInt();
String[] array = inputString.split(" ", n);
System.out.println("Number of words: " + array.length);
for (String arr : array)
System.out.println(arr);
}
}
The simple way to do this is to use String.substring(...) repeatedly to trim N characters off the front of your string ... in a loop.
But if you really want to do this using String.split(...), then I think that the separator regex needs to be a positive look-behind that matches N characters. (It is obscure, and inefficient ... but if regexes are your universal tool ...)
You can use substring for this task.
String sp="StackOverFlow";
int NoOfChars=3;
for(int i=0;i<sp.length();i+=NoOfChars)
{
if(i+NoOfChars<=sp.length())
System.out.println(sp.substring(i,i+NoOfChars));
//Instead add in String ArrayList
else
System.out.println(sp.substring(i));
}
OUTPUT
Sta
ckO
ver
Flo
w
NOTE:Better to use trim() to remove leading or trailing spces
This works for me. In addition to splitting into known lengths, it checks for a null or "too small of a" source string, etc. If a null string is supplied, then a null is returned. If the source string is smaller than the requested split length, then the source string is simply returned.
public static void main (String[] args) throws java.lang.Exception
{
// Three test cases...
String pieces[] = SplitString("Example-for-my-Question", 3);
//String pieces[] = SplitString("Ex", 3);
//String pieces[] = SplitString(null, 3);
if (null != pieces)
{
for (int i = 0; i < pieces.length; i++)
{
System.out.println(pieces[i]);
}
}
}
private static String[] SplitString(String source, int size)
{
String result[] = null;
if (null != source && source.length() > size)
{
int numberOfElements = source.length() / size;
int modulo = source.length() % size;
if (modulo > 0)
{
numberOfElements++;
}
result = new String[numberOfElements];
for (int i = 0; i < numberOfElements; i++)
{
if (numberOfElements - 1 != i)
{
result[i] = source.substring(i * size, (i * size) + size);
}
else
{
result[numberOfElements - 1] = source.substring(i * size, (i * size) + modulo);
}
}
}
else if (null != source)
{
result = new String[1];
result[0] = source;
}
return result;
}
Please try the following program, but here you have to give input to "N" inside the program itself
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}