Char Array to String with classes - java

I am trying to write a class that has methods according to a homework assignment. The class input is a string that is turned into an char array. I want to return the char array as a string inside the method originalChar. Here is my code:
public class Problem5 {
public static void main(String[] args) {
CharacterArray array1 = new CharacterArray("Cool");
System.out.println(array1.originalChar());
}
}
class CharacterArray {
char[] storage;
String formForReturn;
CharacterArray() {
}
CharacterArray(String s) {
char[] storage = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
storage[i] = s.charAt(i);
}
}
public String originalChar() {
String formForReturn = new String(storage);
return formForReturn;
}
}
The error I get is NullPointerException, which to my understanding means I am trying to reference something that doesn't exist. I'm not sure how I troubleshoot this and how to resolve this problem. Some help would be much appreciated.

The way to access instance variable char[] storage; is to use this keyword which represents current object. Otherwise, with your current solution, what you return is empty which causes NullPointerException. Because you create another storage instead of using existing one in the class.
Also you can write your originalChar() method in a shorter way:
class CharacterArray {
char[] storage;
CharacterArray() { }
CharacterArray(String s) {
this.storage = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
storage[i] = s.charAt(i);
}
}
public String originalChar() {
return new String(this.storage);
}
}

Related

Java program to reverse a string not working?

I have written a piece of code to reverse a string in Java. However, its showing multiple errors and I wish to understand where it is that I am going wrong. I know that there are alternative methods of reversing a string. However, I want to know where I am going wrong with my code.
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
Errors:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
Could someone provide me with a resolution?
There are many errors in your code :
For loop condition should be i < len
String rev should be initialized to "" (empty string), else it will throw error when you try to append another string to it.
You can't access characters in a string using str[i], use str.charAt(i) instead.
You are trying to initialize a function (Reverse) inside another function (main), you must initialize it outside the main function.
Also, here is a simple one liner for string reversal:
new StringBuilder(str).reverse().toString()
A good tip might be to use the StringBuilder class whenever you want to do any kind of string manipulation in Java.
Your code has many issues:
You are declaring the method Reverse() inside the main method.
You also need to initialize rev to an empty string.
You can use str.charAt(i) to access each character of the string.
Your for loop goes beyond the string if you use i <= len; so it
should be i < len;.
Your Reverse() method should be static since you are calling it in main
method (which is static)
Here is working code.
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}
Please see the below code:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}
public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}

Converting List<Object> to String returns empty results

Disclaimer : I'm using this Post, as reference for List<Object> to List<String> and this Post for Java List<String> of strings to a JavaScript array.
I've List<Seat> and I want to get all values of it in a comma separated String, I tried in this way
import java.util.*;
import java.lang.*;
class Rextester
{
public Rextester(){
Seat seat1 = new Seat();
seat1.setSeatNumber(1);
Seat seat2 = new Seat();
seat2.setSeatNumber(2);
Seat seat3 = new Seat();
seat3.setSeatNumber(3);
List<Seat> seatList = new ArrayList<Seat>();
seatList.add(seat1);
seatList.add(seat2);
seatList.add(seat3);
Utility util = new Utility();
String stringSeats = util.toJavascriptArray(seatList);
System.out.println("JavaScriptArray is " + stringSeats);
}
public static void main(String args[])
{
new Rextester();
}
private class Seat {
private Integer seatNumber;
public Integer getSeatNumber() {
return this.seatNumber;
}
public void setSeatNumber(Integer seatNumber) {
this.seatNumber = seatNumber;
}
public String toString() {
return ""+ seatNumber;
}
}
private class Utility {
public String toJavascriptArray(List<Seat> listSeats){
List<String> strings = new ArrayList<String>();
for (Seat object : listSeats) {
strings.add(object != null ? object.toString() : null);
}
String[] arr = new String[strings.size()];
arr = strings.toArray(arr);
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr.length; i++){
if(i+1 < arr.length){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
}
}
but this gives me
JavaScriptArray is [,,]
on console, am I making some mistakes? an online working code is http://rextester.com/NDUGT61105
You didn't append iterated element, see below
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]); // add this
if (i + 1 < arr.length) {
sb.append(",");
}
}
have a look at the toString implementations of Arrays and List
Simply you can return
strings.toString()
or
Arrays.toString(arr)
To get the expected result
Another option, if you're using Java 8 is using StringJoiner:
https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
You forgot to append the array elements to the string buffer!
Add
sb.append(arr[i]);
inside the loop where you prepare the string buffer and everything is ok

Remove duplicates in a string in place in JAVA. No additional data structures are allowed

I recently came across this question and I implemented the same as follows:
public class DuplicateRemover
{
public static void removeDuplicates(char[] str)
{
int len = str.length;
boolean[] hit = new boolean[256];
for(int i = 0; i < hit.length; i++)
hit[i] = false;
int noDupindex = 0;
for(int i = 0; i < len; i++)
{
if( !hit[str[i]] )
{
str[noDupindex++] = str[i];
hit[str[i]] = true;
}
}
str[noDupindex] = '\0';
}
public static void main(String[] args)
{
char[] x = "hhhhhhefffff".toCharArray();
removeDuplicates(x);
System.out.println(x);
}
}
But the output shown is "hef hhefffff". The literal '\0' is added to the char array at the end and still while printing it prints the elements after the literal '\0'. Why is it so? Please let me know if I miss something.
x is not a String object. It's an array of char. When you print an array of char, every element is printed. It does not stop on a null char.
Java strings are not terminated by '\0'. You are thinking of C and C++.
The size of an array cannot be changed after its creation, so removeDuplicates can't resize the array. I would recommend that removeDuplicates either returns a new array, or just returns a new String.
Besides above great answers, you could also use StringBuilder in java to align with your original intent as this:
public class DuplicateRemover
{
public static void removeDuplicates(StringBuilder str)
{
int len = str.length();
boolean[] hit = new boolean[256];
for(int i = 0; i < hit.length; i++)
hit[i] = false;
int noDupindex = 0;
for(int i = 0; i < len; i++)
{
if( !hit[str.charAt(i)] )
{
str.setCharAt(noDupindex++, str.charAt(i));
hit[str.charAt(i)] = true;
}
}
str.delete(noDupindex, str.length());
}
public static void main(String[] args)
{
StringBuilder x = new StringBuilder("hhhhhhefffff");
removeDuplicates(x);
System.out.println(x);
}
}
I'd recommend using the null character to signify when to print. As immibis pointed out, Java strings are not terminated by the null character.
However you can create a method to adhere to this.
public static void printString(final char[] str){
int length = str.length;
if(length == 0){
return;
}
int counter = 0;
while(counter < length && str[counter] != 0){
System.out.print(str[counter++]);
}
}
You can then just do:
public static void main(String[] args)
{
char[] x = "hhhhhhefffff".toCharArray();
removeDuplicates(x);
printString(x);
}
Try this example:
public static String trunc(String str) {
char[] buff = {}, tmp = null;
boolean found;
for(char c : str.toLowerCase().toCharArray()) {
found = false;
for(char i : buff) {//search in buff for duplicate
if(i == c) {//found duplicate
found = true;
break;
}
}
if(!found) {//not duplicate
tmp = buff;
buff = new char[buff.length + 1];//new array with +1 size for new character
System.arraycopy(tmp, 0, buff, 0, tmp.length);//copy tmp into buff
buff[tmp.length] = c;//store the new character
}
}
return new String(buff);
}

How to efficiently form array of suffixes?

I was looking for approach make array of suffixes at Java.
I found two ability variants. Moreover I want much more deeply understand differents between this variants.
Includes running time & space.
Code (suffixes):
public static String[] suffixes(String s)
{
int N = s.length();
String[] suffixes = new String[N];
for (int i = 0; i < N; i++)
suffixes[i] = s.substring(i, N);
return suffixes;
}
Code (StringBuilder suffixes):
public static String[] suffixes(String s)
{
int N = s.length();
StringBuilder sb = new StringBuilder(s);
String[] suffixes = new String[N];
for (int i = 0; i < N; i++)
suffixes[i] = sb.substring(i, N);
return suffixes;
}
Question:
How to efficiently form array of suffixes?
There will be no discernable difference between the two ways of doing it that you describe: since Strings in Java are immutable, a new object will be created for each suffix. Making a substring from a String vs. StringBuilder will not give you much difference in performance, compared to allocations and copying required to set up the new string objects.
When you are looking for a suffix, passing the end index is not necessary: use the overload that takes a single int instead:
for (int i = 0; i < N; i++)
suffixes[i] = s.substring(i);
The most efficient way would be to use a char array. However, it won't be so significant as the most costy operation is creating the String objects.
String s = "foobarbaz";
char[] cha = s.toCharArray();
int length = cha.length;
String[] suffixes = new String[length];
for (int i = 0; i < length; ++i)
suffixes[i] = new String(cha, i, length-i);
You could do this, which avoids the substring method,
public String[] suffix(String s)
{
String[] suffixes = new String[s.length()];
String suffix = null;
for (int i = 0 ; i < s.length() ; i++)
{
suffix = suffix == null ? "" + s.charAt(i) : suffix + s.charAt(i);
suffixes[i] = suffix;
}
return suffixes;
}
not sure if it is any faster though.
The only difference between your code snippets is using String or StringBuilder, also you are using it only to retrieve sub string.
subString() from StringBuilder does
new String(offset + beginIndex, endIndex - beginIndex, value);
and subString() from String does
new String(offset + beginIndex, endIndex - beginIndex, value);
both are same and creates new String so there wont be any difference in performance
At the end you always require n + 1 string to complete this task. Only thing that can be optimized is the time when those objects are created.
You could create the string representation as char array and lazy (on demand) return the suffixes.
You can use Iterable and Iterator interfaces to do that:
public class StringSufixies implements Iterable<String> {
private final String input;
public StringSufixies(String input) {
this.input = input;
}
#Override
public Iterator<String> iterator() {
return new SuffixStringIterator(input);
}
private static class SuffixStringIterator implements Iterator<String> {
private final String input;
private final int size;
private int suffixId;
private SuffixStringIterator(String input) {
this.input = input;
this.size = input.length();
this.suffixId = 1;
}
#Override
public boolean hasNext() {
return suffixId <= size;
}
#Override
public String next() {
return input.substring(0, suffixId++); //At this point we create new String
}
#Override
public void remove() {
//Add throw or other impl
}
}
}
You could implement the key functionality over a char array.
private static class SuffixCharIterator implements Iterator<String> {
private final char[] charSequence;
private final int size;
private int suffixId = 0;
private SuffixCharIterator(char[] charSequence) {
this.charSequence = charSequence;
this.size = charSequence.length;
}
#Override
public boolean hasNext() {
return suffixId <= size;
}
#Override
public String next() {
return new String(charSequence, 0, suffixId++); //At this point we create a new String
}
#Override
public void remove() {
}
}
But IMHO is more complex and we do not gain nothing.
The advantage of this solution is that you can work on results and decide to stop before all prefixes are created.

Parse string into double

My code doesn't seem to work when the string token is an int. Here it is:
public class CO2Data {
CO2Data dataSet[] = new CO2Data[10];
String strLine = "Italy 476.08 116.86 2 592";
int lines = 10;
double roadCO2;
public void saveLineInfo(String strLine, int lines) {
StringTokenizer token = new StringTokenizer(strLine);
String str = "hello";
int count = 0;
for (int i = 0; i < lines; i++) {
while (token.hasMoreTokens()) {
str = token.nextToken();
if (count == 3) {
getRoadCO2(str, roadCO2);
dataSet[i].setRoadCO2(roadCO2);
}
count++;
}
}
}
public double getRoadCO2(String str, double roadCO2) {
roadCO2 = Double.parseDouble(str);
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
}
In the rest of the lines, roadCO2 is a double, so I'm guessing my program is getting confused? How do I fix it? Thanks so much!
You are getting NullPointerException because,
You've declared an Array of CO2Data dataSet[] = new CO2Data[10];,
but every element inside this CO2Data[] array is pointing to Null.
Hence, this call: dataSet[i].setRoadCO2(roadCO2); will generate a NullPointerException
because dataSet[i] is pointing to null.
Solution :
Instantiate dataSet[i] = new CO2Data();
then call dataSet[i].setRoadCO2(roadCO2);
I'd recommend changing the names of the parameters to your methods to something slightly different than the class datamember "roadCO2". That might help you sort out the error :)
When I ran your code, I got a NullPointerException at line 22. This is beacuse the array 'data' has not been initialized.
You can initialize your array as follows
for(int i = 0; i < dataSet.length; i++) {
dataSet[i] = new CO2Data();
}

Categories