Merging of one int and string array into third array - java

There are 2 arrays, one of int and one of Strings (words) ; sort both of them and then print it in a way that at odd places it should be words and at even numbers.
This is my code:
import java.util.*;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int num[]=new int[10];
String str[]=new String[10];
String str1[]=new String[20];
for(int i=0; i<5; i++)//for taking strings
{
str[i]=in.next();
}
for(int i=0; i<5; i++)//for taking nums
{
num[i]=in.nextInt();
}
for(int i=0; i<5; i++)
{
System.out.println("The String are "+str[i]);
}
for(int i=0; i<5; i++)
{
System.out.println("The num are "+num[i]);
}
for (int i = 0; i < 5; i++) //for sorting nums
{
for (int j = i + 1; j < 5; j++)
{
if (num[i]>(num[j]))
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
for (int i = 0; i < 5; i++)// for sorting strs
{
for (int j = i + 1; j < 5; j++)
{
if (str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
System.out.println("The sorted strings are:");
for(int i=0; i<10; i++)//for merging both
{
if((i+1)%2==0)
{
int k=0;
str1[i]=String.valueOf(num[k]);
System.out.println("The String are "+str1[i]);
k++;
}
else
{
int j=0;
str1[i]=str[j];
System.out.println("The String are "+str1[i]);
j++;
}
}
/* for(int i=0; i<10; i++)
{
System.out.println("The String are "+str1[i]);
}
*/
}
}
What I am getting the output:
The sorted strings are:
The String are ab
The String are 1
The String are ab
The String are 1
The String are ab
The String are 1
The String are ab
The String are 1
The String are ab
The String are 1
It's only taking the first element of both arrays.

You should initialize k and j to 0 before the loop, not inside the loop.
int k=0;
int j=0;
for(int i=0; i<10; i++)//for merging both
{
if((i+1)%2==0)
{
str1[i]=String.valueOf(num[k]);
System.out.println("The String are "+str1[i]);
k++;
}
else
{
str1[i]=str[j];
System.out.println("The String are "+str1[i]);
j++;
}
}

You can user Arrays class to sort the arrays.
String[] strArray = new String[] {"a","z","q","p"};
Arrays.sort(strArray);
Similarly, try to 2nd array.
Now, declare another array by adding size of two arrays:
String[] newArray = new String[sum];
int j=0;
for(int i=0;i<newArray.length;i+=2)
{
newArray[i]=strArray[j];
newArray[i+1] = otherArray[j++];
}

Other people has pointed the root cause. Beside this, why you initialize the arrays num[] str[] str1[] with capacity 10(and 20), which is a double of the needed capacity 5(and 10) ?
Another issue is that the name of str1[] is really bad.

Related

Program that removes duplicated elements and return its new elements and size

My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}

line 21 show ; expected

The first line contains a single integer p denoting the length of array. The second line contains space-separated integers describing each respective element in array. The third line prints an integer indicating the number of negative arrays.
package asgn3;
import java.util.*;
public class Asgn3 {
public static void main(String[] args) {
int count = 0, result = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the array ");
String s = in.nextLine();
int j = 0;
String[] s1 = s.split(" ");
int a[] = new int[s1.length];
for(String s2:s1) {
a[j] = Integer.parseInt(s2));
j++;
}
for (int i = 0; i < a.length; i++) {
for ( j = i; j < a.length; j ++) {
for (int k = i; k <= j; k++) {
result += a[k];
}
if(result < 0)
count ++;
}
System.out.println("no. of negatve arrays is "+count);
}
}
}
The issues is usage of extra unnecessary parenthesis. Change,
a[j]=Integer.parseInt(s2));
with
a[j]=Integer.parseInt(s2);
Remove extra bracket ) from end of line
a[j] = Integer.parseInt(s2);

ArrayIndexOutOfBoundsException when trying to find the determinant of a 2D Array/Matrix

this is my first Stack Overflow post, and I am fairly new to java, so I may not initially comprehend some of the feedback you give me.
With this program, I am supposed to find the determinant of a matrix recursively with a size determined by the user. When I do so, however, I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Determinant.Copy<Determinant.java:55>
at Determinant.det<Determinant.java:31>
at Determinant.main<Determinant.java:15>
I understand what this error means, but I don't understand why it's happening.
Here are the classes I am using (both printmatrix and the main method were written by my teacher, I had to complete the Copy and det methods):
import javax.swing.JOptionPane;
public class Determinant
{
public static void main(String args[])
{
String sizeStr = JOptionPane.showInputDialog("What size?");
int size = Integer.parseInt(sizeStr);
int[][] matrix = new int[size][size];
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
matrix[i][j] = (int)(Math.random()*40)-20;
printArray(matrix);
System.out.println("\nThe determinant = "+det(matrix));
}
public static int det(int[][] A)
{
int answer = 0;
int place = 0;
int[][] temp;
int[][] temp1;
if(A.length==1){
return(A[0][0]);
}
for(int i = 0; i<A.length; i++){
temp = new int[A.length-1][A[0].length-1];
temp1 = Copy(temp, i);
if(i%2==0){
place = 1;
}
else{
place = -1;
}
answer = answer + place * A[0][i] * det(temp1);
}
return answer;
}
public static int[][] Copy(int[][] B, int i)
{
int[][] C = new int[B.length-1][B.length-1];
for(int j = 1; j<B.length; j++){
for(int k = 0; k<B[0].length; k++){
if(k>i){
C[j-1][k-1]=B[j][k];
}
else{
C[j-1][k]=B[j][k];
}
}
}
return C;
}
public static void printArray(int[][] A)
{
for(int i=0; i<A.length; i++)
{
for(int j=0; j<A.length; j++)
{
int num = A[i][j];
if(num<-9)
System.out.print(" ");
else if(num<0||num>9)
System.out.print(" ");
else
System.out.print(" ");
System.out.print(A[i][j]);
}
System.out.println();
}
}
}
The error occurs at the else statement in Copy and temp1 = Copy(temp, i).
I am confused, as if either j or k = 1, shouldn't that be a position in the array? What am I missing?
The size of C array in method copy, should be same as B array.
Reason: You are copying B array into C array, they should have same size.
Try the following:
import javax.swing.JOptionPane;
public class Determinant
{
public static void main(String args[])
{
String sizeStr = JOptionPane.showInputDialog("What size?");
int size = Integer.parseInt(sizeStr);
int[][] matrix = new int[size][size];
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
matrix[i][j] = (int) (Math.random() * 40) - 20;
}
}
printArray(matrix);
System.out.println("\nThe determinant = "+det(matrix));
}
public static int det(int[][] A)
{
int answer = 0;
int place = 0;
int[][] temp;
int[][] temp1;
if(A.length==1){
return(A[0][0]);
}
for(int i = 0; i<A.length; i++){
temp = new int[A.length-1][A[0].length-1];
temp1 = Copy(temp, i);
if(i%2==0){
place = 1;
}
else{
place = -1;
}
answer = answer + place * A[0][i] * det(temp1);
}
return answer;
}
public static int[][] Copy(int[][] B, int i)
{
//The C array size should be same as B
int[][] C = new int[B.length][B[0].length];
for(int j = 1; j<B.length; j++){
for(int k = 0; k<B[0].length; k++){
if(k>i){
C[j-1][k-1]=B[j][k];
}
else{
C[j-1][k]=B[j][k];
}
}
}
return C;
}
public static void printArray(int[][] A)
{
for(int i=0; i<A.length; i++)
{
for(int j=0; j<A.length; j++)
{
int num = A[i][j];
if(num<-9)
System.out.print(" ");
else if(num<0||num>9)
System.out.print(" ");
else
System.out.print(" ");
System.out.print(A[i][j]);
}
System.out.println();
}
}
}
Hope this explains, enjoy!
You should declare your matrix in Copy function in this way:
int[][] C = new int[B.length][B[0].length];
Otherwise you are declaring a matrix without a row and column. The fact that you start to use from 0 doesn't mean you should declare one row in less!

Generate rotations of a string, java

Suppose, I have a string "big$". I need the following :
big$
ig$b
g$bi
$big
I also need to store these strings in an ArrayList.
Can someone please help me. I am unable to think of a solution.
This is what I have done. I am able to print it but I don't know how to store them.
private static void rotations(String str) {
int n = str.length();
char temp;
String temp1 = null;
for(int i=0; i<n; i++){
System.out.println();
for(int j=i+1; j<n; j++)
System.out.print(str.charAt(j));
for(int k=0; k<=i; k++)
System.out.print(str.charAt(k));
}
}
You are very close, just instead of printing out each char append it to a String variable inside your loop, then add that variable to an ArrayList<String>
private static List<String> rotations(String str) {
int n = str.length();
char temp;
String temp1 = null;
List<String> retval = new ArrayList<String>();
for(int i=0; i<n; i++){
StringBuilder sb = new StringBuilder();
for(int j=i+1; j<n; j++)
sb.append(str.charAt(j));
for(int k=0; k<=i; k++)
sb.append(str.charAt(k));
retval.add(sb.toString());
}
return retval;
}
And you can print those out in your main method:
public static void main (String[] args)
{
List<String> rotations = rotations("big$");
for(String s : rotations)
{
System.out.println(s);
}
}
Try this code:
String a = "big$";
char[] array = a.toCharArray();
List<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++)
{
String temp = "" + array[i];
for( int j = i+1; j < array.length + i; j++)
{
temp += array[j%(array.length)];
}
list.add(temp);
}
A simple sample of ArrayList:
ArrayList<String> container = new ArrayList<String>();
container.add("A");
container.add("B");
container.add("C");
for (int i = 0; i < container.size(); i++) {
System.out.println(container.get(i));
}

I have to fill a 2D array with characters and let people search for words (Java)

So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
System.out.println("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut

Categories