Generate rotations of a string, java - java

Suppose, I have a string "big$". I need the following :
big$
ig$b
g$bi
$big
I also need to store these strings in an ArrayList.
Can someone please help me. I am unable to think of a solution.
This is what I have done. I am able to print it but I don't know how to store them.
private static void rotations(String str) {
int n = str.length();
char temp;
String temp1 = null;
for(int i=0; i<n; i++){
System.out.println();
for(int j=i+1; j<n; j++)
System.out.print(str.charAt(j));
for(int k=0; k<=i; k++)
System.out.print(str.charAt(k));
}
}

You are very close, just instead of printing out each char append it to a String variable inside your loop, then add that variable to an ArrayList<String>
private static List<String> rotations(String str) {
int n = str.length();
char temp;
String temp1 = null;
List<String> retval = new ArrayList<String>();
for(int i=0; i<n; i++){
StringBuilder sb = new StringBuilder();
for(int j=i+1; j<n; j++)
sb.append(str.charAt(j));
for(int k=0; k<=i; k++)
sb.append(str.charAt(k));
retval.add(sb.toString());
}
return retval;
}
And you can print those out in your main method:
public static void main (String[] args)
{
List<String> rotations = rotations("big$");
for(String s : rotations)
{
System.out.println(s);
}
}

Try this code:
String a = "big$";
char[] array = a.toCharArray();
List<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++)
{
String temp = "" + array[i];
for( int j = i+1; j < array.length + i; j++)
{
temp += array[j%(array.length)];
}
list.add(temp);
}

A simple sample of ArrayList:
ArrayList<String> container = new ArrayList<String>();
container.add("A");
container.add("B");
container.add("C");
for (int i = 0; i < container.size(); i++) {
System.out.println(container.get(i));
}

Related

I can't stop null from showing up in my output for my 1d array in java

I am struggling to declare i as an interger and I can't figure out why the output is coming out as null. The goal is to make a sequence
My code is:
public static void main(String[] args) {
String[] myArray = new String[10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
}
The problem is that none of the items inside the array has value, therefore they are null.
You can use the following code which initialize all item whith an empty string in the first loop:
for (int i = 0; i < 10; i++) {
myArray[i] = "";
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
public static void main(String[] args) {
String[] myArray = new String[10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
}
At this line
myArray[i] = myArray[i] + "A";
myArray[i] at the right side is null, so concatinating "A" with a null will make it null again. You should initialize each myArray[i] as Answered by Amir MB or can try this:
public static void main(String[] args) {
String[] myArray = new String[10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
myArray[i] = "A" + myArray[i];
}
System.out.println(myArray[i]);
}
}
for (int i = 0; i < 10; i++) {
myArray[i] = "";
for (int j = 0; j <= i; j++) {
myArray[i] = myArray[i] + "A";
}
System.out.println(myArray[i]);
}
String[] myArray = new String[10];
This is an object array and all objects are initialized to null, if there is no explicit value assigned to it.
So, each element of the array needs to be assigned to a empty string; do it in the first for loop as mentioned above.
Or, assign values during array declaration itself. Worth for a small sized array, but won't recommend for a larger one.
String[] myArray = new String[]{"", "", "", "", "", "", "", "", "", ""};
Arrays class has a fill method.
String[] myArray = new String[10];
Arrays.fill(myArray, "");

Placing an array into a file column column

I currently have a .txt file with one line that looks like:
xxxxxxxxxxxxxxxxxxxxx
I would like to place that one line into a 2d array so my file can come out like so:
xxxxxxx
xxxxxxx
xxxxxxx
Here's my java class:
import java.util.*;
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("TextFile.txt"));
String line = in.readLine();
String[][] e = new String[5][3];
// fill array
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
e[i][j] = line;
}
}
// print array
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
System.out.println(e[i][j]);
break;
}
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
When I run my java class, all I get is this which's not what I want:
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxx
You have to either use a 2D array of char or 1D array of String
'String' class is already internally implemented as an array of 'Char'.
Just use a 1D array of String, like:
String[] e = new String[3];
// fill array
for(int i = 0; i < e.length; i++) {
e[i] = line;
}
// print array
for(int i = 0; i < e.length; i++) {
System.out.println(e[i]);
}
The 2D version would be something like below (not recommended)
String line = in.readLine();
Char[][] e = new Char[3][5];
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
e[i][j] = line.charAt(j);//to access element at jth index of string
}
}
// print array
for(int i = 0; i < e.length; i++) {
for(int j = 0; j < e.length; j++) {
System.out.print(e[i][j]);
}
System.out.println()
}
Anyways for printing you do not to store in array, just do:
int noOfRows = 3;
for(int i=0;i<noOfRows;i++){
System.out.println(line)
}
You could just iterate over the string like this:
String line = "xxxxxxxxxxxxxxxxxxxxx";
int colums = 7;
for (int i = 0; i < line.length(); i++) {
System.out.print(line.charAt(i));
if ((i + 1) % colums == 0) {
System.out.println();
}
}
A more declarative version is possible when using Guava's Splitter:
for (String token : Splitter.fixedLength(coluns).split(line)) {
System.out.println(token);
}

Merging of one int and string array into third array

There are 2 arrays, one of int and one of Strings (words) ; sort both of them and then print it in a way that at odd places it should be words and at even numbers.
This is my code:
import java.util.*;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int num[]=new int[10];
String str[]=new String[10];
String str1[]=new String[20];
for(int i=0; i<5; i++)//for taking strings
{
str[i]=in.next();
}
for(int i=0; i<5; i++)//for taking nums
{
num[i]=in.nextInt();
}
for(int i=0; i<5; i++)
{
System.out.println("The String are "+str[i]);
}
for(int i=0; i<5; i++)
{
System.out.println("The num are "+num[i]);
}
for (int i = 0; i < 5; i++) //for sorting nums
{
for (int j = i + 1; j < 5; j++)
{
if (num[i]>(num[j]))
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
for (int i = 0; i < 5; i++)// for sorting strs
{
for (int j = i + 1; j < 5; j++)
{
if (str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
System.out.println("The sorted strings are:");
for(int i=0; i<10; i++)//for merging both
{
if((i+1)%2==0)
{
int k=0;
str1[i]=String.valueOf(num[k]);
System.out.println("The String are "+str1[i]);
k++;
}
else
{
int j=0;
str1[i]=str[j];
System.out.println("The String are "+str1[i]);
j++;
}
}
/* for(int i=0; i<10; i++)
{
System.out.println("The String are "+str1[i]);
}
*/
}
}
What I am getting the output:
The sorted strings are:
The String are ab
The String are 1
The String are ab
The String are 1
The String are ab
The String are 1
The String are ab
The String are 1
The String are ab
The String are 1
It's only taking the first element of both arrays.
You should initialize k and j to 0 before the loop, not inside the loop.
int k=0;
int j=0;
for(int i=0; i<10; i++)//for merging both
{
if((i+1)%2==0)
{
str1[i]=String.valueOf(num[k]);
System.out.println("The String are "+str1[i]);
k++;
}
else
{
str1[i]=str[j];
System.out.println("The String are "+str1[i]);
j++;
}
}
You can user Arrays class to sort the arrays.
String[] strArray = new String[] {"a","z","q","p"};
Arrays.sort(strArray);
Similarly, try to 2nd array.
Now, declare another array by adding size of two arrays:
String[] newArray = new String[sum];
int j=0;
for(int i=0;i<newArray.length;i+=2)
{
newArray[i]=strArray[j];
newArray[i+1] = otherArray[j++];
}
Other people has pointed the root cause. Beside this, why you initialize the arrays num[] str[] str1[] with capacity 10(and 20), which is a double of the needed capacity 5(and 10) ?
Another issue is that the name of str1[] is really bad.

Hi, trying to print a certain amount of character based on array values. Java

so my question is how could I print a certain amount of characters based on a array value?
So currently I have an array declared globally like this
static float timesOccured [] = {5,3,7,3,1};
In a method called draw I've tried a few things to try and get it so the output would be something along the line like this
|||||
|||
|||||||
|||
|
Could anyone help me out?
Much appreciated.
You would need to use nested for loops as I have done below:
for (int i = 0; i < timesOccured.length; i++) {
for (int j = 0; j < timesOccured[i]; j++) {
// print characters here
}
}
Loop through the timesOccured array and get each entry; and use the entry (i.e. timesOccured[i]) to print your lines in the nested for loop.
I hope this helps.
public class PrintChar {
static float timesOccured [] = {5,3,7,3,1};
public static void draw(){
for(int i=0; i<timesOccured.length;i++){
for(int j=0; j< timesOccured[i]; j++){
System.out.print("!");
}
System.out.println();
}
}
public static void main(String[] args) {
draw();
}
}
Here are seven ways to do it:
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Strings;
public class StringRepeat {
static int timesOccured[] = { 5, 3, 7, 3, 1 };
static String s = "|";
static String t = "||||||||||||||||||";
public static String repeat(int j) {
return (t.substring(0, j));
}
public static void main(String[] args) {
System.out.println("Using native Java String.substring");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(repeat(timesOccured[i]));
}
System.out.println("\nUsing native Java char.replace");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(new String(new char[timesOccured[i]]).replace("\0", s));
}
System.out.println("\nUsing native Java String.format.replace");
String result = "";
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(String.format(String.format("%%0%dd", timesOccured[i]), 0).replace("0",s));
}
System.out.println(result);
System.out.println("\nUsing native Java StringBuilder.append");
for (int i = 0; i < timesOccured.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < timesOccured[i]; j++) { sb.append(s); };
System.out.println(sb.toString());
}
System.out.println("\nUsing native Jave double for loops");
for (int i = 0; i < timesOccured.length; i++) {
String u = "";
for (int j = 0; j < timesOccured[i]; j++) {
u = u + s;
}
System.out.println(u);
}
System.out.println("\nUsing org.apache.commons.lang.StringUtils.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(StringUtils.repeat(s, timesOccured[i]));
}
System.out.println("\nUsing com.google.common.base.Strings.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(Strings.repeat(s, timesOccured[i]));
}
}
}

How can I store substrings generated from a String into a String array?

The program I am writing is to generate every possible sub-string from a given string (including the word itself) and store these into a String array
This is my code:
String word = "WOMAN";
String[] res = new String[20];
String sub;
int i, j, k;
int len = word.length();
for(i = 0; i < len; i++)
{
for(j = 0; j <= len-i; j++)
{
sub = word.substring(i, i+j);
for(k = 0; k < res.length; k++)
res[k] = sub;
}
}
I get an error that says - error: incompatible types: String[] cannot be converted to String. What am I doing wrong?! I want to store each sub-string as an element in the res array.
public static String[] getSubStrings(String string){
List<String> result = new ArrayList<String>();
int i, c, length;
length = string.length();
for( c = 0 ; c < length ; c++ )
{
for( i = 1 ; i <= length - c ; i++ )
{
result.add(string.substring(c, c+i));
}
}
return result.toArray(new String[result.size()]);
}
i change little maybe for some help
String word = "WOMAN";
String[] res = new String[20];
String sub;
int i, j, k=0;
int len = word.length();
for(i = 0;i < len;i++)
{
for(j = 0;j <= len-i;j++,k++)
{
sub = word.substring(i, i+j);
//for(k = 0;k < res.length;k++)
res[k] = sub;
}
}
Try it this way
String word = "WOMAN";
String sub = "";
int len = word.length();
List list = new ArrayList();
for(int i = 0; i < len; i++)
{
for(int j = 1; j <=len-i; j++)
{
sub = word.substring(i, i+j);
list.add(sub);
}
}
System.out.println(list);
Try Using ArrayList in place of array . Array Size is fixed . So generated sub strings can sometimes over flow or some spaces remain empty if sub string size will be less than the array. Array list grows dynamically with the increasing size .
with Array list one simple solution would be :
public class GenerateStrings {
/**
* Generate substrings of a given string and add them in an arraylist.
*/
public static void main(String[] args) {
ArrayList<String> aList=new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter the string to split");
String string=sc.nextLine();
for(int i=0;i<string.length();i++){
for(int j=1;j<=string.length()-i;j++){
String subString=string.substring(i, i+j);
aList.add(subString);
}
}
System.out.println(aList);
}
}
I Hope it helps .
I simplified your code to this one. This might help.
String str = "WOMAN";
List<String> tempArr = new ArrayList<String>();
for (int i = 1; i < str.length(); i++) {
for (int j = i; j <= str.length(); j++) {
tempArr.add(str.substring(i - 1, j));
}
}
String[] res = tempArr.toArray(new String[tempArr.size()]);

Categories