Arrays.toString, no library - java

I'm going bonkers on my java assignment. I'm rather new to methods and I can't seem to get my head around this one. Could you perhaps give me a guiding hand?
I'm trying to convert an array of int to a string and print it using the. toString method. We are not allowed to use some libraries though. All I get from my code is a 'stack overflow'...
Code:
public static void main(String[] args) {
int[] arr = {3,4,5,6,7};
String str = toString(arr);
System.out.println("arr = " + str);
}
private static String toString(int[] arr) {
String str = Arrays.toString(arr);
return str;
}
This is the complete code of my program so far:
public class Arrays {
public static void main(String[] args) {
int[] arr = {3,4,5,6,7};
int result = sum(arr);
System.out.println(result);
String str = toString(arr);
System.out.println("arr = " + str);
}
private static int sum(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
}
private static String toString(int[] arr) {
String str = Arrays.toString(arr);
return str;
}
}
The result in my console:
25
Exception in thread "main" java.lang.StackOverflowError
at tb222kc_lab3.Arrays.toString(Arrays.java:24)
at tb222kc_lab3.Arrays.toString(Arrays.java:24)
at tb222kc_lab3.Arrays.toString(Arrays.java:24).....

Change your Arrays.toString(arr) in toString Method to java.util.Arrays.toString(arr)
Your code has gone into recursive call because you have named your class as Arrays

Then I will create my own toString like this :
public String toString(int[] arr) {
StringBuilder result = new StringBuilder();
result.append("[");
for (int a : arr) {
result.append(a);
}
result.append("]");
return result.toString();
}

Your toString() method should look like this:
private static String toString(int[] arr) {
String str = "[";
for (int index = 0; index < arr.length; index++) {
// Concat the string with the int value.
str += arr[index];
// Add delimiter only if we're not at the last index.
if (index < arr.length - 1) {
str += ", ";
}
}
str += "]";
return str;
}
I will only add to this that college professors are notorious for giving their students requirements that have no bearing on real life (like don't use libraries).

Related

Reverse String Method type mismatch error java

I am trying to use a method to reverse the characters in a string and I keep getting a type mismatch error. Any thoughts?
public static String userReverse (String userEntry3) {
String reverse = "";
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse = System.out.println(userEntry3.charAt(i));
}
return reverse;
}
System.out.println is a void method. It returns nothing. So it cannot assigned back to a String variable
Your code is wrong.
If you want to reverse a string, you can use this:
public static String userReverse (String userEntry3) {
return new StringBuilder(userEntry3).reverse().toString()
}
Get rid of System.out.println and add a += to concatenate the new char
public static String userReverse (String userEntry3) {
String reverse = "";
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse += userEntry3.charAt(i);
}
return reverse;
}
EDIT: As Tim said in the comments, StringBuilder can be used too (and is better practice than concatenating strings in a loop):
public static String userReverse (String userEntry3) {
StringBuilder reverse = new StringBuilder();
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse.append(userEntry3.charAt(i));
}
return reverse.toString();
}
A more optimized way to reverse a string includes two pointer approach:
Use one pointer to start from the beginning and the other to start from the end. By the time they meet each other your string is already reversed
public static String userReverse (String userEntry3) {
int i = 0;
int j = userEntry3.length()-1;
StringBuilder myName = new StringBuilder(userEntry3);
for(; i < j ; i++,j--){
char temp = userEntry3.charAt(i);
myName.setCharAt(i,userEntry3.charAt(j));
myName.setCharAt(j,temp);
}
return myName.toString();
}
System.out.println() is a void method and it not return anything. you should try it this way,
public static String userReverse (String userEntry3) {
String reverse = "";
for (int i = (userEntry3.length() -1); i >= 0 ; i--) {
reverse += userEntry3.charAt(i).toString();
}
return reverse;
}

Reverse a String , Code was not working properly

I think theres something wrong with my syntax. So please help me with those syntax:
public class Main {
public static void main(String arg[]) {
String number = "1234";
System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, .charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
Reverse function is not working properly.
StringBuilder has a function that does this:
StringBuilder.reverse() You can also append .toString() to this call to get it back into a String.
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse()
There were some errors in your code.
1) error: illegal start of expression builder.setCharAt(i, .charAt(otherEnd));
correction: builder.setCharAt(i, **builder**.charAt(otherEnd));
2) error: non-static method inPlaceReverse(String) cannot be referenced from a static context
This is because you have declared main() as static whereas your isPlaceReverse() is non-static. You cannot reference a non-static member within a static member.
Change your function definition to public **static** String inPlaceReverse(final String input)
After you make the above corrections, you'll get the desired output:
public class Main {
public static void main(String args[]) {
String number = "1234";
System.out.println("original String: " + number);
String reversed = inPlaceReverse(number);
System.out.println("reversed String: " + reversed);
}
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd)); // swap
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
Output
original String: 1234
reversed String: 4321
Update your reverse logic to :
public static String inPlaceReverse(final String input) {
final StringBuilder builder = new StringBuilder(input);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final char otherEnd = builder.charAt(length - i - 1);
builder.setCharAt(i, otherEnd); // swap
builder.setCharAt(length-i-1, current);
}
return builder.toString();
}
A more appropriate way will be:
public static String inPlaceReverse(final String input) { // make it static
final StringBuilder builder = new StringBuilder(input);
return builder.reverse().toString();
}

Replacing substrings with Strings not using replace()

The problem is: mutation() is passed two Strings and returns a String. Every occurrence in the first String of fzgh is replaced with the second String.
mutation("Hello. I want an fzgh. Give me an fzgh now.", "IPhone 6")-> "Hello. I want an IPhone 6. Give me an IPhone 6 now."
Here's my attempt:
public static String mutation(String s, String t){
int f=s.indexOf("fzgh");
String w="";
if(f !=-1){
w=w+s.substring(0,f)+t;
}
return w;
}
I know there's .replace(), but we are not allowed to use it. We have to use indexOf()
You can define mutation like this
public static String mutation(String s,String t){
int f=s.indexOf("fzgh");
int l =4;//length of "fzgh"
String w = s;
while(f!=-1){
w=w.substring(0,f)+t+w.substring(f+l,w.length());
f=w.indexOf("fzgh");
}
return w;
}
This will remove all the "fzgh" from String s and will replace them with String t.
This can be easily solved if you can use split and join methods.
public static String mutation(String s, String t) {
return String.join(t, s.split("fzgh"));
}
split will split the input string around "fzgh" and return an array of String, in this case, it will return ["Hello. I want an ", ". Give me an ", " now."]. Now you can join the each element together with "IPhone 6" by using join method.
Notice that join is introduced in Java8.
But if you should only indexOf and substring to solve this problem, the code would be more complicated, but not so complex.
public static String mutation(String s, String t) {
StringBuilder sb = new StringBuilder();
int p = 0, q = 0;
while ((q = s.indexOf("fzgh", p)) >= 0) {
sb.append(s.substring(p, q));
sb.append(t);
p = q+4;
}
sb.append(s.substring(p));
return sb.toString();
}
Its kinda clumsy but there you go, i will edit meanwhile if u need explanation :)
*Edit: its not good enough yet, will try to fix it. This is kinda other way around, kinda different solution but not that good, will delete it if i fail to fix.
*Edit #2: Fixed
import java.util.Scanner;
import java.io.*;
class Mutation
{
public static String mutation(String s, String t){
String toBeReplaced = "fzgh";
int sizeOfThatString = toBeReplaced.length();
String[] array = s.split(" ");
for (int i = 0; i < array.length; i++) {
String tempString= array[i];
if(tempString.length()>sizeOfThatString) {
if(tempString.contains(toBeReplaced)) {
String other = array[i].substring(sizeOfThatString);
array[i] = t+other;
}
}
if(tempString.equals(toBeReplaced)) {
array[i] = t;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if(i!=array.length) {
sb.append(array[i]+" ");
}
else {
sb.append(array[i]);
}
}
return sb.toString();
}
public static void main(String[] args) {
Arabic_Randomizer ar= new Arabic_Randomizer();
System.out.println(ar.mutation("Hello. I want an fzgh. Give me an fzgh now.", "IPhone 6"));
}
}
use this code
public class run {
public static String mutation(String w,String s, String t){
String toBeReplaced = w;
int sizeOfThatString = toBeReplaced.length();
String[] array = s.split(" ");
for (int i = 0; i < array.length; i++) {
String tempString= array[i];
if(tempString.length()>sizeOfThatString) {
tempString = array[i].substring(0,sizeOfThatString);
System.out.println("TempString " +tempString);
}
if(tempString.equals(w)) {
array[i] = t;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if(i!=array.length) {
sb.append(array[i]+" ");
}
else {
sb.append(array[i]);
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(mutation("fzgh","Hello. I want an fzgh. Give me an fzgh now.", "IPhone 6"));
}
}
out:
TempString Hell
TempString fzgh
Hello. I want an IPhone 6 Give me an IPhone 6 now.

Getting error trying to reverse a string in Java

I'm trying to do a simple reverse task like: change the string "how are you" to "you are how".
this is my code:
public class Program {
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String [] retString = new String[givenString.length];
int last = givenString.length - 1;
for (int i = 0; i < givenString.length; i++) {
retString [i] = givenString[last--];
}
return retString.toString();
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
I'm getting a weird output:
[Ljava.lang.String;#e76cbf7
The output isn't "weird" at all - it's the Object's internal string representation, created by Object.toString(). String[] doesnt override that. If you want to output all entires, loop through them and concatenate them, Best using a StringBuilder to avoid creating unnecessary String instances.
public static String arrayToString (String[] array) {
StringBuilder result = new StringBuilder();
for (String value : array) {
result.append(value);
}
return StringBuilder.toString();
}
If you don'T need that method on it'S own and want to include it in the overall process of reversing the sentence, this is how it may look. It iterates only once, iterating backwards (= counting down) to reverse the sentence.
public static String revSentence (String str) {
String [] givenString = str.split(" ");
StringBuilder result = new StringBuilder();
// no need for 'last', we can use i to count down as well...
for (int i = givenString.length - 1 ; i >= 0; i--) {
result.append(givenString[i]);
}
return result.toString();
}
[Edit]: because of the OPs comment to one of the other answers, about not having learned how to use StringBUilder yet, here is a arrayToStirng method without using one. Note however that this should not be done normally, as it creates useless instances of String whiche are not cleaned up by the GC because of the immutable nature of String(all instances are kept for reuse).
public static String arrayToString (String[] array) {
String result = "";
for (String value : array) {
result += value;
}
return result;
}
Or, without a dedicate arrayToString method:
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String result = "";
for (int i = givenString.length-1 ; i >= 0 ; i--) {
result += givenString[i];
}
return result;
}
Here is a solution:
public class Program {
public static String revSentence (String str) {
String retString = "";
String [] givenString = str.split(" ");
for (int i=givenString.length-1; i>=0; i--) {
retString += givenString[i] + " ";
}
return retString;
}
public static void main(String[] args) {
String m = "how are you";
System.out.print(revSentence(m));
}
}
Modified it to make the "revSentence" function return a String, plus improved the code a bit. Enjoy!
Calling toString() on an array object (in your case retString) doesn't print all array entries, instead it prints object address.
You should print array entries by iterating over them.
Use this code for reversed string
StringBuilder builder = new StringBuilder();
for(String s : retString) {
builder.append(s);
}
return builder.toString();
Calling toString on an array gives you the memory ref which isn't very useful. Try this:
public static String revSentence (String str) {
String[] givenString = str.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
sb.append(givenString[i]);
if (i != 0)
sb.append(" ");
}
return sb.toString();
}
the for loop start from greater length to lower and builder.append(givenString[i] + " "); this will concatenate String and return whole sentence you are how you could use both mySentence += givenString[i] + " "; or builder.append(givenString[i] + " "); but the best way is to use StringBuilder class (see docs)
public class Program {
public static String revSentence(String str) {
String[] givenString = str.split(" ");
String[] retString = new String[givenString.length];
int last = givenString.length - 1;
//String mySentence = "";
StringBuilder builder = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
// retString [i] = givenString[i];
// mySentence += givenString[i] + " ";
builder.append(givenString[i] + " ");
}
return builder.toString(); // retuning String
//return mySentence;
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
Faster, and shorter:
To reverse a word, use:
public String reverseWord(String s) {
StringBuilder y = new StringBuilder(s);
return y.reverse();
}
Now split and use this method and use Stringbuidler.append to concatenate the all.
And dont forget the space inbetween.

I want to split string without using split function?

I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

Categories

Resources