Java Array Error - java

New to java programming and I am currently trying to create a class similar to ArrayList using Arrays.
Am trying to add elements to an array and expand the array by copying them to a new array of bigger size.
I am getting an out of index error at 20.
Code may be messy but currently really stuck.
public class MyArrayList{
private String[] strings;
private int arraySize;
private int storedStrings;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
storedStrings = 0;
for (int i = 0; i < this.arraySize;i ++){
if (strings[i] != null){
storedStrings = storedStrings +1;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
strings[i] = newArray[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize = this.arraySize +10;
}
else{
strings[storedStrings] = string;
}
for(int i = 0; i < strings.length; i++)
{
//System.out.println(strings[i]);
}
}
}
The code is being run in the test class where the error is being generated on line 10 of test class and line 47 of MyArrayList class.
This is the test code
public class TestArrayList{
public static void main(String[] args)
{
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
}
}

you can do it like this:
public void addString(String string){
if (storedStrings == this.arraySize){
this.arraySize += 10;
String[] newArray = new String[this.arraySize];
for (int i = 0; i < this.storedStrings; i++){
newArray[i] = strings[i];
}
this.strings = newArray;
}
if (strings[storedStrings] == null){
strings[storedStrings++] = string;
}
// remove this loop it will show repeating values otherwise
for(int i = 0; i < storedStrings; i++)
{
System.out.println(strings[i]);
}
}
edit: as you are new to java always think about how can you do more with less code, how to avoid repetition of code, how to merge things that do common task. That will help you write better code
edit2 : the problem is with this loop
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
if you have 50 elements in array the getString method on (eg) i = 25 will be 25*5 = 125 which is not the index in the array that's why you are getting ArrayIndexOutOfBound Exception.
you can add
public int size(){
return storedStrings;
}
to check the size of your list which is the maximum item that is inside the list

First with your code there is a mistake in this line
strings[i] = newArray[i];
because you arenĀ“t copying the old data to new array but cleaning the strings array, I suppose that you wish do the contrary action.
In other hand you have extra code that you could improve.

public class MyArrayList{
private String[] strings;
private int arraySize;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
// Since you always do this
// it's better to use a local variale
int storedStrings = 0;
// Use the foreach syntax
// it's less prone to errors
// and easier to read
for (String s : this.strings){
if (s != null){
storedStrings++;
}else{
// since you want to count the strings in your array
// and you put them in this array
// one after the other
// no need to check the whole array
// when you find null you can exit the loop
break;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
// here we need to copy the content of strings in newArray
// NOT the other way
newArray[i] = this.strings[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize += 10;
}else{
this.strings[storedStrings] = string;
}
}
public String[] getStrings(){
return this.strings;
}
}
As for the test class
public static void main(String[] args){
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (String s : a.getStrings()){
System.out.println(a);
}
}

Related

How to print out results in NQueens

I am new to JAVA. Below is my code of NQueens problem. The results are [[Ljava.lang.String;#123a439b, [Ljava.lang.String;#7de26db8].
Can anyone please help? Thank you very much! I copyied the code from other's blog. The code should be correct. I just don't know how to print out the results. I think this should be not very hard. My background is not computer science, that's maybe why I have the trouble. Thank you!
import java.util.ArrayList;
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> res = new ArrayList<String[]>();
if(n<=0)
return res;
int [] columnVal = new int[n];
DFS_helper(n,res,0,columnVal);
return res;
}
public void DFS_helper(int nQueens, ArrayList<String[]> res, int row, int[] columnVal){
if(row == nQueens){
String[] unit = new String[nQueens];
for(int i = 0; i < nQueens; i++){
StringBuilder s = new StringBuilder();
for(int j = 0; j < nQueens; j++){
if(j == columnVal[i])
s.append("Q ");
else
s.append("+ ");
}
unit[i] = s.toString();
//System.out.println(unit[i]);
}
//System.out.println();
res.add(unit);
// System.out.println(Arrays.toString(res));
//return;
}
else{
for(int i = 0; i < nQueens; i++){
columnVal[row] = i;//(row,columnVal[row)==>(row,i)
if(isValid(row,columnVal))
DFS_helper(nQueens, res, row+1, columnVal);
}
}
}
public boolean isValid(int row, int [] columnVal){
for(int i = 0; i < row; i++){
if(columnVal[row] == columnVal[i]
||Math.abs(columnVal[row]-columnVal[i]) == row-i)
return false;
}
return true;
}
public static void main(String[] args) {
Solution su = new Solution();
int n = 4;
System.out.println(su.solveNQueens(n));
}
}
While you do System.out.println(su.solveNQueens(n)); it prints list contents which are array and it just prints array object, but not it's contents. so, to print array contents you need to iterate through them.
Arrays.toString Returns a string representation of the contents of the specified array.
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])
get result into a list and then print it:
List<String[]> res = su.solveNQueens(n);
for(String strs[] : res) {
System.out.println(Arrays.toString(strs));
}
You can do like this too as the above prints with ,. Here iterating through the list and then array.
List<String[]> res = su.solveNQueens(n);
for(String strs[] : res) {
for(String s: strs) {
System.out.print(s+ " ");
}
System.out.println();
}
in java 8, you can make use of stream and lambda:
ArrayList<String[]> result = su.solveNQueens(n)
result.stream().forEach(i->System.out.println(Arrays.toString(i)));

Java array I need your thought

Given an array of strings, return another array containing all of its longest strings.
For (String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};)
output will be
{"serm", "sazi" , "kart"}.
The following code is wrong, What can I do to fix it.
public class Tester {
public static void main(String[] args) {
Tester all = new Tester();
String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};
String [] y = all.allLongestStrings(x);
System.out.println(y);
}
String[] allLongestStrings(String[] input) {
ArrayList<String> answer = new ArrayList<String>(
Arrays.asList(input[0]));
for (int i = 1; i < input.length; i++) {
if (input[i].length() == answer.get(0).length()) {
answer.add(input[i]);
}
if (input[i].length() > answer.get(0).length()) {
answer.add(input[i]);
}
}
return answer.toArray(new String[0]);
}
}
I will give you solution, but as it homework, it will be only sudo code
problem with your solution is, you are not finging longest strings, but strings same size or bigger than size of first element
let helper = []
let maxLength = 0;
for each string in array
if (len(string) >maxLength){
maxLength = len(string);
clear(helper)
}
if (len(string) == maxLength)
helper.add(string)
}
return helper;
You can try below code
private static String[] solution(String[] inputArray) {
int longestStrSize = 0;
List<String> longestStringList = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != null) {
if (longestStrSize <= inputArray[i].length()) {
longestStrSize = inputArray[i].length();
longestStringList.add(inputArray[i]);
}
}
}
final int i = longestStrSize;
return longestStringList.stream().filter(x -> x.length() >= i).collect(Collectors.toList()).stream()
.toArray(String[]::new);
}

Alternate display of 2 strings in Java

I have a java program where the following is what I wanted to achieve:
first input: ABC
second input: xyz
output: AxByCz
and my Java program is as follows:
import java.io.*;
class DisplayStringAlternately
{
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
displayStringAlternately(firstC, secondC);
}
public static void displayStringAlternately (String[] firstString, String[] secondString)
{
int combinedLengthOfStrings = firstString.length + secondString.length;
for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
{
if(counter % 2 == 0)
{
System.out.print(secondString[i]);
}
else
{
System.out.print(firstString[i]);
}
}
}
}
however I encounter the following runtime error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
Java Result: 1
What mistake is in my Java program?
If both arrays have same length for loop should continue while i < anyArray.length.
Also you don't need any counter to determine from which array you should print first. Just hardcode that first element will be printed from firstString and next one from secondString.
So your displayStringAlternately method can look like
public static void displayStringAlternately(String[] firstString,
String[] secondString) {
for (int i = 0; i < firstString.length; i++) {
System.out.print(firstString[i]);
System.out.print(secondString[i]);
}
}
Anyway your code throws ArrayIndexOutOfBoundsException because each time you decide from which array print element you are incrementing i, so effectively you are jumping through arrays this way
i=0 i=2
{"A","B","C"};
{"x","y","z"};
i=1 i=3
^^^-here is the problem
so as you see your code tries to access element from second array which is not inside of it (it is out of its bounds).
As you commented, If both arrays length is same, you can simply do
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
Then
for(int i = 0; i < firstC.length; i++) {
System.out.print(firstC[i]);
System.out.print(secondC[i]);
}
Using the combined length of the Strings is wrong, since, for example, secondString[i] would cause an exception when i >= secondString.length.
Try the below working code with high performance
public static void main(String[] arguments)
{
String firstC[], secondC[];
firstC = new String[] {"A","B","C"};
secondC = new String[] {"x","y","z"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < firstC.length; i++) {
builder.append(firstC[i]);
builder.append(secondC[i]);
}
System.out.println(builder.toString());
}
public class concad {
public void main(String[] args) {
String s1 = "RAMESH";
String s2 = "SURESH";
int i;
int j;
for (i = 0; i < s1.length(); i++) {
System.out.print(s1.charAt(i));
for (j = i; j <= i; j++) {
if (j == i) {
System.out.print(s2.charAt(j));
}
}
}
}
}
I have taken two strings as mentioned.Then pass one counter variable in inner for-loop with second string,Then for every even position pass with code "counter%2".Check this out if any concern then comment below.
public class AlternatePosition {
public static void main(String[] arguments) {
String abc = "abcd";
String def = "efgh";
displayStringAlternately(abc, def);
}
public static void displayStringAlternately(String firstString, String secondString) {
for (int i = 0; i < firstString.length(); i++) {
for (int counter = 1, j = 0; j < secondString.length(); counter++, j++) {
if (counter % 2 == 0) {
System.out.print(secondString.charAt(i));
break;
} else {
System.out.print(firstString.charAt(i));
}
}
}
}
}

How do you copy the components of an ArrayList to a regular Array?

public boolean makeReservation(int id, AvilaNatalyPassenger request) {
boolean status = true;
ArrayList<Integer> inputValues = new ArrayList<Integer>();
for (int i = 0; i < 22; i++) {
for (int j = 0; j < 5; j++) {
id = seats[i][j];
if (id != -1) {
if (inputValues.contains(id)) {
status = false;
break;
}
else {
inputValues.add(id);
for(int a = 0; a < inputValues.size; a++)
seats[a] = inputValues[a];
}
}
}
}
return status;
}
This is what I have but its not correct. I need to add what I have in inputVaule arrayList into the array seats.
You can also look at the Java API: http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html
public Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
So this is what you could do:
seats[a] = inputValues.toArray();
Furthermore you cannot use inputValues[a] since it is not an array. What you probably could do is
seats[a] = (inputValues.toArray())[a];
To answer your question, here is an example:
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Example is taken from here

why am i getting a null pointer when converting string to int array?

My main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf("First integer: %s \n", firstInt.display());
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result = "";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
You did not instantiate your array. You need something like:
private int[] intArray = new int[SIZE];
where size is the length of your array.
You are not initialize the array intArray, that way you are getting error, here is the complete program
import java.util.Scanner;
class TestForNull {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf ("First integer: %s \n", firstInt.display());
}
}
and this is LargeInteger
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
private int[] intArray;
Member variables are null by default, so you need to initialize this.
Most likely you want it the same size as your string:
public LargeInteger(String s) {
intArray = new int[s.length()]; // Create the actual array before you try to put anything in it
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
Or you should use a container that resizes itself, like ArrayList.
Diferent approach through Integer.parseInt
Integer.parseInt("yourInt");
To achieve your goal:
String a = "12345667788" //sample
String b = "";
int [] vecInt = new int[a.length()]; // The lack of initialization was your mistake as the above stated
for(int i=0; i< a.length(); i++)
{
b = a.substring(0,1);
a= a.substring(1);
vecInt[i] = Integer.parseInt(b);
}
Please be aware of Double, long have far higher range then Integer which might be enough in your case to avoid an array!
you forgot to initialize the array intArray
I would recommend to use a java.util.List
You forgot to initialize the array. You have written it in constructor and the variables declared in method or constructor needs to be initialize at the same time.
Note : Implementing your logic in Constructor is not recommended unless and until you dont have any other choice.

Categories