How do I print an array as a String from a method? - arrays

I'm trying to print my array separated by pipes ("|"), but it keeps printing before the println statement in my main method. It should look like this:
90|0|-12|25|10412|445|-32|1
I've been messing with the return statement, but I can't think of anything else to do.
static String arrayToString(int[] input){
String toString = "";
for (int i = 0; i < input.length; i++){
if (i > 0){
System.out.print("|");
} else if (i == input.length - 1){
System.out.print("");
}
System.out.print(input[i]);
}
return toString;
}
public static void main(String[] args) {
int[] testArray1 = {90, 0, -12, 25, 10412, 445, -32, 1};
CommonArrayAlgorithms testingObject = new CommonArrayAlgorithms();
System.out.println("Testing arrayToString");
String arrayString;
arrayString = testingObject.arrayToString(testArray1); //<--- prints here
System.out.println(" arrayToString returned: " + arrayString); //<--- should print here
My output is:
Testing arrayToString
90|0|-12|25|10412|445|-32|1 arrayToString returned:
When it should be:
Testing arrayToString
arrayToString returned: 90|0|-12|25|10412|445|-32|1

In your method you are outputting to the console with System.out.print where you should be adding to your toString variable.
Change you method as follows (keeping your current logic):
static String arrayToString(int[] input){
String toString = "";
for (int i = 0; i < input.length; i++){
if (i > 0){
toString += "|";
} else if (i == input.length - 1){
toString += "";
}
toString += input[i];
}
return toString;
}

It is because you are calling the method that prints the array before your title string, and also your method returns an empty string that you tried to store on another string and print it after your title.
So the solution for this :
System.out.print("your title: "+testingObject.arrayToString(array1));

Related

Java - Search only working for array [0], remaining array items returning "not found"

In the following method, searching for an item name that is included in the array should return "(item name) was found and its product id is (item array ID)".
This works for item [0], but if any other item name is entered, they return "That product was not found".
private int findProduct() {
System.out.println("Enter the item to search for:");
while (true) {
for (int i = 0; i < products.length; i++) {
String itemToFind = getNextStringLineFromUser();
String searchText = products[i];
if (searchText.equals(itemToFind)) {
System.out.println(itemToFind + " was found and its product id is " + i);
return i;
}
System.out.println("That product was not found");
return -1;
}
}
}
If anyone has an idea of why this issue is happening, I would be very grateful for some advice on how to resolve the problems.
Thank you in advance for any help.
I got you.
The reason why your method is only right when the target is at index 0, is that your method returns -1 when first time not matched, without examining the other array element. (When a method returned, it terminated.)
Modify and check your code, you will see.
private int findProduct() {
System.out.println("Enter the item to search for:");
while (true) {
for (int i = 0; i < products.length; i++) {
String itemToFind = getNextStringLineFromUser();
String searchText = products[i];
if (searchText.equals(itemToFind)) {
System.out.println(itemToFind + " was found and its product id is " + i);
return i;
}
System.out.println("That product was not found"); // line 1
return -1; // line 2
}
}
}
The line 1 and 2 I commented, should be placed out of the for-loop. If you put them at where they are now, they will be run after the above if-statement run.
So if the first element of array matches with itemToFind, it works normal. When the first element does not match with itemToFind, the below line 2 will be run, your method terminates right away at a wrong timing.
The right code should be:
private int findProduct() {
System.out.println("Enter the item to search for:");
String itemToFind = scanner.nextLine(); // receive the entered string
for (int i = 0; i < products.length; i++) {
String searchText = products[i];
if (searchText.equals(itemToFind)) { // check if matched
System.out.println(itemToFind + " was found and its product id is " + i);
return i; // exit the method
}
}
System.out.println("That product was not found");
return -1;
}

Permutation of a string so that the patterns match

The question is to count how many permutations of a string B have an equivalent pattern into a bigger string A. For example, if A="aabbccd" and B="xx", then it should print 3, since "aa", "bb", "cc" are all substrings of A which share the same pattern as B.
I have tried to pass the substrings as numbers, such as xx becomes "11" and do the same for string A, but I still can't get it to work. Any ideas? Length can be up to 10^7.
Here's the code for changing pattern:
void transform(int* dest, char* original, int len) {
int j=1;
Al[original[0]-'a']=j;
dest[0]=j;
j++;
for (int i=1;i<len;i++) {
if (Al[original[i]-'a']==0)
Al[original[i]-'a']=j++;
dest[i]=Al[original[i]-'a'];
}
}
Concept: Use Regular Expressions
You would need the following regular expression (\\w)\\1{(REPETITIONS-1)}
I don't know about C but Java provides a library to compile RegEx patterns. Here's a class that implements just what you want:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPatternPermutation {
public static void main(String[] args) {
int REPETITIONS = 3;
String REGEX = "(\\w)\\1{" + (REPETITIONS-1) + "}";
String INPUT = "abbbbbbccddeffff";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
int count = 0;
while(m.find()){
String match = m.group();
System.out.println(match);
count++;
}
System.out.println(count);
}
}
Here's a test of the code above: https://ideone.com/5nztaa
Here's a useful website to test any RegEx: https://regexr.com/
Without Regular Expressions
public class StringPatternPermutation {
public static void main(String[] args) {
String a = "abjjjiixsssppw";
String b = "qwwwee";
String patternA = detectPattern(a);
String patternB = detectPattern(b);
System.out.println("-String A: " + a);
System.out.println("-Pattern A: " + patternA);
System.out.println("-String B: " + b);
System.out.println("-Pattern B: " + patternB);
System.out.println("-A contains B? " + patternA.contains(patternB));
int count = 0;
int index = 0;
while((index = patternA.indexOf(patternB)) != -1){
count++;
patternA = patternA.substring(index+1, patternA.length());
}
System.out.println("-Number of occurances: " + count);
}
private static String detectPattern(String a){
StringBuilder sb = new StringBuilder();
char prev = a.charAt(0);
int count = 1;
for(int i = 1; i < a.length(); i++){
char curr = a.charAt(i);
if(curr == prev)
count++;
else {
sb.append(count + ", ");
prev = curr;
count = 1;
}
if(i == a.length() - 1){
sb.append(count);
}
}
return sb.toString();
}
}
Test it on ideOne: https://ideone.com/w422Du

If the input is a1bc2def3 output should be abcbcdefdef

If the given input is a1bc2def3 then output should be abcbcdefdefdef
Whenever the number comes then we should repeat previous substring that many number of times.
Please provide the algorithm or code to accomplish this.
Here's another approach that doesn't rely on regex.
public String splitRepeat(String str)
{
StringBuilder out = new StringBuilder();
boolean number = false;
for(int i=0,j=0,k=0; i<=str.length(); i++)
{
if(i==str.length() || Character.isDigit(str.charAt(i)) != number)
{
if(number)
{
for(int r = Integer.parseInt(str.substring(j, i)); r>0; r--)
{
out.append(str.substring(k, j));
}
}
else
{
k=j;
}
j=i;
number = !number;
}
}
return out.toString();
}
My suggestion would be:
Try using regex so you can get an array of numbers and characters,
then convert the number Parsable elements of the array into an integer,
after that loop with the index of the arrays to append n-times the characters of the array
then print the final result
Example:
public static void main(String[] args) {
String stringToProcess = "a1bc2def3";
String[] regexSplitted = stringToProcess.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
String appender = "";
for (int i = 0; i < regexSplitted.length; i++) {
try {
int kilo = Integer.parseInt(regexSplitted[i]);
for (int j = 0; j < kilo; j++) {
sb.append(appender).append(regexSplitted[i - 1]);
appender = "-";
}
} catch (NumberFormatException e) {
}
}
System.out.println(sb.toString());
}
this will print
a-bc-bc-def-def-def
that is pretty much what you are looking for.

Printing String from a char array?

Currently the code should replace all spaces in a string with %20. For the most part, I think the logic is right on the method I make a call to, but when I want to see the returned result I my main method prints nothing -- it prints a blank for the string. Could someone direct me where my my logic in turning the array into a string is incorrect? Thanks for the time and help. I attached my code for the method in case you guys needed it. Sorry if the mistake is dumb.
public class replaceSpaces {
public static void main(String[] args) {
char[] data = checkfor20("yo o");
String text = String.valueOf(data); //turn char array into string representation
System.out.println(" new one: " + text);
}
private static char[] checkfor20(String string) {
int check = string.length(); //length of string
int spaceCount = 0, newLength; //count spaces and new length with %20 put in
char[] charstring = string.toCharArray(); // turn string into char array
for(int i = 0; i < check ; i++) { //get space count for newlenght
if (charstring[i] == ' ') {
spaceCount++;
}
}
newLength = check + (spaceCount * 2);
char[] newArray = new char[newLength];
for(int i = check - 1; i >= 0; i--) {
if(newArray[i] == ' ') { //get spaces and put it
newArray[newLength - 1 ] = '0';
newArray[newLength - 2 ] = '2';
newArray[newLength - 3 ] = '%';
newLength = newLength - 3;
}
else {
newArray[newLength - 1] = charstring[i];
newLength = newLength - 1;
}
}
return newArray; //return the new char array
}}
Why not newstring = oldstring.replace(" ","%20");?
Apologizes for the mistake on my part I was supposed to just change my array into
if(charstring[i] == ' ')
rather than the new array I created.

Creating a static method

Here's my code.
public static String hBlanks(String a, String b){
StringBuilder blanks = new StringBuilder();
int j;
for(int x = 0; x < a.length(); x++){
blanks.append('-');
}
System.out.println(blanks);
String strBlanks = blanks.toString();
for(int i = 0; i < a.length(); i++){
j = 0;
while(j < b.length()){
boolean check = a.contains(b.charAt(j));
//I keep getting an error on the boolean check = a.contains(b.charAt(j)); line. It says: "contains(java.lang.CharSequence) in java.lang.String cannot be applied to (char)"
if(check == true){
strBlanks = blanks.replace('-', "" + a.charAt(i));
//And I get another error at the str = strBlanks.replace('-', "" + a.charAt(i)); line. That one says "cannot find symbol
symbol : method replace(char,java.lang.String)
location: class java.lang.String"
}else{
j++;
}
}
return strBlanks;
}
}
To get rid of your compilation issues,
Change strBlanks.replace('-', "" + a.charAt(i)); to
strBlanks.replace('-', a.charAt(1));
Also change a.contains(b.charAt(j)); to
a.contains("" + b.charAt(1));
How about just one line, instead of all that code:
public static String wordBlanks(String a, CharSequence b){
return a.replaceAll("[^" + b + "]", "-");
}
This works by creating a regex that matches every character not in b and using that to replace ever occurrence in a with a dash.

Resources