String to Character Array - arrays

I have a problem with my code below:
public class stringToChar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] sCharArr;
String[] odd = new String[n];
String[] even = new String[n];
for(int i = 0; i < n; i++) {
sCharArr = in.next().toCharArray();
for(int j = 0; j < sCharArr.length; j++) {
if(j % 2 == 0)
even[i] += sCharArr[j];
else
odd[i] += sCharArr[j];
}
}
for(int i = 0; i < n; i++) {
System.out.println(even[i] + " " + odd[i]);
}
}
}
My issue is on the output it has a Null in the result. Here is a sample scenario:
2
John
Cena
Answer should be:
Jh on
Cn ea
But my code answer is:
NullJh Nullon
NullCn Nullea

Your problem is that the new arrays are initialized with all null Strings. Then your code is not assigning values to all array elements, but just to some of them!
Finally you print your array, and surprise, those values that were null and that have not been changed - are still null (and when you print a null string ... it prints "null" [ yes, null, not Null; you got a little mistake there in your output example ]
You see, you iterate from 0 to the length of your two arrays. And if the number is even, you put a value in the even[i]; and if the value is odd, it goes to odd[i]. Lets take even - in that case, odd[i] simply stays null!
One way to fix that:
List<String> even = new ArrayList<>();
List<String> odd = new ArrayList<>();
And now, instead of setting a certain index in even/odd; you simply do:
even.add(some new value);
and to add those single characters:
even.add(new String(sCharArr));
Doing so, even and odd will (in the end) contain exactly the values that you added to each list; but no "residual" nulls. For the record: the way how you split up strings, to then pull them back into a String array isn't exactly the most simple/straight forward way to solve the problem.
But I leave "further" simplifications" as exercise to the user.

Related

Deleting Elements in Array equal to a value

I'm trying to make a code that removes all the elements from the array that are equal to a given value. For example an array = [hi, hello, hi, bye] value = hi, it would given an output hello bye
Here's my code:
int count = 0;
for(int i=0; i<stringArr.length;
if(stringArr[i].equals(value)){
count--;
for(int j= i; j<stringArr.length-1; j++){
stringArr[j] = stringArr[j+1];
}
i--;
}
}
Problem is instead of the expected output as: hello bye
It gives an output of:
hello hi bye bye
Try Java stream api:
String value = "hi";
String[] stringArr = new String[] {"hi", "hello", "hi", "bye"};
String[] results = Arrays.stream(stringArr)
.filter(it -> !it.equalsIgnoreCase(value))
.toArray(String[]::new);
The problem is that you are shifting the values left but not decrementing the length of the array in the outer for.
Assign stringArr.length to count and use it in the for.
Trading memory for speed, you could create a new array of the same length and only add in the first occurrence of what you want.
String[] removeEqual(String[]array,String val){
boolean found =false;
String[]out=new String[array.length];
int count=0;
for (int i=0;i<array.length;i++){
if(array[i].equals(val)){
if(!found){
out[count++]=val;
found=true;
}
else out[count++]=val;
}
}
return Arrays.copyOf(out, count);
}
You may like to consider separate functions for separate conditions such as removeLessThan and removeGreaterThan to keep it functionally coherent.
I don't recommend to do any manipulation to the original array, create a new one. Recycling is good for the planet, but may be very harmful in code. So if you want to stick to the Arrays only, then create a new array with and add all elements you want into the new array, but I think you can do better. Your approach is very "C" like, this is Java, you have a lot of better tools, than arrays.
One of them are streams and lambdas like this
#Test
public void example_lambdas() {
String[] array = {"hi", "hello", "hi", "bye"};
String[] result = Arrays.stream(array).filter(element -> !"hi".equals(element)).toArray(String[]::new);
System.out.println(Arrays.toString(result));
}
Another option is to use list
#Test
public void example_list() {
String[] array = {"hi", "hello", "hi", "bye"};
List<String> list = new ArrayList<>(Arrays.asList(array));
Set<String> toBeRemoved = Collections.singleton("hi");
list.removeAll(toBeRemoved);
String[] result = list.toArray(new String[0]);
System.out.println(Arrays.toString(result));
}
An array has a fixed size that cannot be changed. Hence your result cannot be a two element array when you start with a four element array. If you want the result to be a two element array, then you will need to create a second array. If, however, you want the result to stay in the original array, then I suggest setting the excess array elements to null. The following code demonstrates.
String[] stringArr = {"hi", "hello", "hi", "bye"};
String condition = "==";
String value = "hi";
int count = stringArr.length;
for (int i = 0; i < count; i++) {
if (condition.equals("==")) {
if (stringArr[i].equals(value)) {
count--;
for (int j = i; j < stringArr.length - 1; j++) {
stringArr[j] = stringArr[j + 1];
}
stringArr[stringArr.length - 1] = null;
}
}
}
System.out.println(java.util.Arrays.toString(stringArr));
The above code prints the following:
[hello, bye, null, null]
EDIT
As requested, below code creates a new array that only contains the requested elements, i.e. the ones that were not removed from the original array.
String[] stringArr = {"hi", "hello", "hi", "bye"};
String condition = "==";
String value = "hi";
String[] temp = new String[stringArr.length];
int count = 0;
for (int i = 0; i < stringArr.length; i++) {
if (condition.equals("==")) {
if (!stringArr[i].equals(value)) {
temp[count++] = stringArr[i];
}
}
}
String[] result = new String[count];
for (int i = 0; i < count; i++) {
result[i] = temp[i];
}
System.out.println(Arrays.toString(result));
The above code prints the following:
[hello, bye]
In other words, result is a two element array.
Note that I assume that you only want to do array manipulation and you don't want to use classes in the JDK that most of the other answers have used.

Removing the last element in an array

This is a question about finding distinct values in an array of ten numbers. The user provides 10 numbers. I've written the code, separated the code into two files(another condition to the assignment) but I found myself at a loss when the answer returns with a trailing 0.
I need to know how to remove the trailing 0 from the array. If it was a string I could do this easily. Unfortunately, I need to return the answer as an array between the two files.
I have researched the topic and found that "splice" works but I can't figure out how it works in my code. The only solution that I came up with is to remove all 0s from the code (my first example below). Unfortunately, the user should be able to include 0s if he or she decides to input a zero.
//document 1
public static void main(String[] args){
Scanner s = new Scanner(System.in);
String strOfArray = " ";
String Values = "";
int arr[]=new int[1000000];
System.out.print("Entered 10 integers:\t\t\t ");
for(int i = 0; i<10; i++)
arr[i] = s.nextInt();
for (int j=0; j<10; j++)
strOfArray += (arr[j]+ " ");
System.out.println ("Array before processing:"+ "\t" + strOfArray);
System.out.print("Array after processing:\t\t ");
DistinctValues.getValues(arr);
}
}
//document 2
public class DistinctValues {
public static void getValues(int[] arr){
String Values = "";
for (int i=0; i<arr.length; i++){
boolean isUnique = false;
for(int j=0; j<i; j++){
if (arr[i] == arr[j]){
isUnique = true;
break;}}
if(!isUnique){
System.out.print(arr[i] +" ");}}}}
I added all my code for better clarification. Thank you.
So here's the solution after trial and error and me realizing that I had a set number of elements so I didn't need to be ambiguous about what I set "i" to. Since I have 10 variables, I could just make it i one less than 10 and the program couldn't spit out an extra 0.
if(!isUnique && i<10){
System.out.print(arr[i] +" ");}
But since I'm learning this. Can someone help me with an array that wasn't set to 10 integers or set to however many the user wanted. Make it i < variable?

How to iterate backwards through an array?

I want to take each value from the end of the array and iterate backwards to the middle of the array, adding each value to a string:
for (int x = testArray.length - 1; x > testArray.length/2; x--){
b+=testArray[x];
}
It doesn't seem to work because when I print b it is an empty space. Is it possible to iterate backwards through an array and add the values to a string. They are all String values.
One thing to note is that if the array's length is an odd number, then your code wont work, since the length divided by 2 would be a decimal. Convert the middle index to an int. You should be using StringBuilder too if you're using quite a bit of concatenations.
String[] names = {", and Henry, ", ", David", "Bob"};
StringBuilder allNames = new StringBuilder();
for (int i = names.length - 1; i >= (int) names.length/2; i--)
{
allNames.append(names[i]);
}
System.out.println(allNames);
String b = "";
for (int x = testArray.length - 1; x > testArray.length/2; x--){
b+=testArray[x];
}
System.out.println(b);

Count numbers in a string and add them to array

I have a string that a user inputs through Console.ReadLine() e.g. "140 150 64 49" (separated only with spaces) and I want to add those numbers to an array. What is the best way to do it. I'm kinda new to programming so I'm a bit lost. Google didn't help either.
When saying you're using Console.ReadLine(), I assume you use C#.
you can use this:
int counter = 0;
int[] array = new int[200]; // choose some size
string s = Console.ReadLine();
int indexOfNextSpace;
while ((indexOfNextSpace = s.IndexOf(' ')) > -1)
{
int num = int.Parse(s.Substring(0, indexOfNextSpace));
array[counter] = num;
counter++;
s = s.Substring(indexOfNextSpace + 1);
}
if you're not sure about valid input, try surrounding with try\catch, or use int.TryParse instead of int.Parse.
You can use this:
List<int> ints = new List<int>();
int num;
int[] result = new int[] { };
string input = Console.ReadLine();
foreach (string str in input.Split(' '))
{
if (int.TryParse(str, out num))
{
ints.Add(num);
}
}
result = ints.ToArray();
foreach (int i in result)
{
Console.WriteLine(i);
}
It uses a List then convert it to array. Note that items are validated, so only ints are added.
This will produce the following output:
123 456 dsf def 1
123
456
1

toString() implementation for Array

Before I state my question, I would like to thank everyone who helped me on my previous question. Anywho, I am currently getting the memory offsets as result even when I place it to the to a toString method. I've read most of the questions regarding the toString method and have somewhat of a understanding, I just wanted to make sure if I'm implementing this correctly. If you feel that this is a redundant question, I understand. Thanks for the help in advance.
Ship class
import java.util.Scanner;
public class Ship{
int type;
public String [][] shipPiece = new String[11][11];
Scanner in = new Scanner(System.in);
//Coordinate xy = new Coordinate();
//private Coordinate[] bawdPiece = {new section()};
public Ship(){
}
public String[][] placeShip()
{
System.out.println();
for(int x = 1; x<10; x++)
{
for(int y = 1; y<10; y++)
{
shipPiece[x][y] = "0";
System.out.print("|" + shipPiece);
}
}
return shipPiece;
}
public String toString()
{
StringBuilder temp = new StringBuilder();
temp.append(shipPiece);
return temp.toString();
}
public String toString()
{
StringBuilder temp = new StringBuilder();
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
temp.append(String.valueOf(shipPiece[x][y]);
}
temp.append("\n");
}
return temp.toString();
}
Also another thing I would like to point out is your array initialization. You initialize it with 11 x 11 indices, but your loop is only adding 9 values to each row and column Loop starts at 1 and ends at 9. You may want to fix your initialization to 10 x 10 and make your loop start at 0.
If I understand the question correctly, you are trying to get the index of the shipPiece as a string?
If that's the case try String.ValueOf(index), you'll obviously have to do this twice as you have a 2-dimensional array.
Ex:
String s = String.ValueOf(xIndex) + "," + String.ValueOf(yIndex);

Resources