How to pass multiple array to constructor in java? - java

I have a problem passing a multiple array to constructor.
Can we actually do that or not?
public class First {
public String[] a;
public String[] b;
public First(String[] a, String[] b){
this.a=a;
this.b=b;
}
}
And the next code is where I'm using class First.
Scanner ss = new Scanner(System.in);
int x;
System.out.print("How many lines? ");
x = ss.nextInt();
for(int i=0; i<x; i++){
System.out.print("A: "); a[i]=ss.nextString();
System.out.print("B: "); b[i]=ss.nextString();
}
First ff= new First(a,b);
In NetBeans, there is no error, but I can't use it in another class.
I'd be thankful if you would help me.

There is nothing wrong with passing in multiple arrays to a Java constructor. However, you may want to consider making copies of the arrays that you are passing in (with Arrays.copyOf()). You should also seriously consider making your actual array data private or protected.

The Question is not cleared. You cant use it on another class means. PLease clear your question.. But below code is working fine.. you can check it out.
public class MultipleArr {
String a[];
String b[];
public MultipleArr(String[] a, String[] b)
{
this.a=a;
this.b=b;
}
public static void main(String[] args) {
String [] a={"1","2","3"};
String [] b={"2","2","3"};
MultipleArr arr=new MultipleArr(a,b);
for(int i=0;i<arr.a.length;i++)
{
System.out.println(arr.a[i]);
}
for(int i=0;i<arr.b.length;i++)
{
System.out.println(arr.b[i]);
}
}
}

public class MultipleArr {
String a[];
String b[];
public MultipleArr(String[] a, String[] b)
{
this.a=a;
this.b=b;
}
public static void main(String[] args) {
String [] a;
String [] b;
Scanner ss = new Scanner(System.in);
int x;
System.out.print("How many lines? ");
x = ss.nextInt();
a=new String[x];
System.out.print("A: ");
for(int i=0; i<x; i++)
{
a[i]=ss.next();
}
b=new String[x];
System.out.print("B: ");
for(int i=0; i<x; i++)
{
b[i]=ss.next();
}
MultipleArr arr=new MultipleArr(a,b);
for(int i=0;i<arr.a.length;i++)
{
System.out.println(arr.a[i]);
}
for(int i=0;i<arr.b.length;i++)
{
System.out.println(arr.b[i]);
}
}
}

Related

Why is array giving a wrong value when using two classes?

I have this code here.
public class ArrayChallenge {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of integers: ");
int num = kb.nextInt();
int [] returnedArray = readIntegers(num);
System.out.println("Ascending Order: " + printAsc(returnedArray));
}
public static int [] readIntegers(int count){
int [] values = new int[count];
for(int i=0; i<count; i++){
System.out.print("Enter number: ");
values[i] = kb.nextInt();
}
return values;
}
public static int [] printAsc(int [] theArray){
Arrays.sort(theArray);
return theArray;
}
The code above works perfectly fine. I have only one class but several static methods and during calling the method printAsc(returnedArray), the program will return a set of arrays in a format just like using .toString
I took this code to a next level using two classes and making the static methods to instance methods. However when i print the arrays. It prints these values [I#643b1d11
Here is my code below:
Main Class
public class Main {
public static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the number of elements: ");
int num = kb.nextInt();
int numArrays [] = new int[num];
Minimum minimum = new Minimum();
int [] returnedArrays = minimum.readIntegers(numArrays);
int returnedMin = minimum.findMin(returnedArrays);
System.out.println("Minimum Value: " + returnedMin);
System.out.println("Ascending Arrays: " + minimum.arrayAsc(returnedArrays));
}
}
Minimum Class
public class Minimum {
public int [] readIntegers(int [] numArrays){
System.out.println("Enter " + numArrays.length + " integers:");
for(int i=0; i< numArrays.length; i++){
numArrays[i]=Main.kb.nextInt();
}
return numArrays;
}
public int findMin(int [] numArrays){
int max = Integer.MAX_VALUE;
for(int i=0;i<numArrays.length;i++){
if(max>numArrays[i]){
max = numArrays[i];
}
}
return max;
}
public int [] arrayAsc(int [] numArrays){
Arrays.sort(numArrays);
return numArrays;
}
}
How did the result of my arrays became like that? Can someone explain the process to me? Much appreciate.
Also, i used the debug method because im using Intellij, It didnt really show anything.
The way you are using printAsc, you need to change its definition to return a String.
public static String printAsc(int [] theArray){
Arrays.sort(theArray);
return Arrays.toString(theArray);
}
If you do not want to change the definition of printAsc, you need to call it as follows:
System.out.println("Ascending Order: " + Arrays.toString(printAsc(returnedArray)));
You can't just print an Array and expect it to read out all the values. When printing, Java casts the value into a String. By default, when dealing with Objects, Java will simply print the name of the Object's class and its Hash value. This is what you see. You can read more about it here.
If you want to parse the Array into a String that hold all the members of the Array, you might want to take a look at the Arrays.toString method (and how to use it).

How to call method which is not void in the main driver?

I created the following java program in which a Statement in the form of String is taken. All the words of that statement are stored in the array separately.
Example - String statement = "hello world i love dogs";
get stored in the array as - {hello, world, i, love, dogs}
I wrote the following code, but I am not able to check it since when I call the methods in the main method, it don't work as required.
How can I get the output?
public class Apcsa2 {
/**
* #param args the command line arguments
*/
public String sentence;
public List<Integer> getBlankPositions(){
List<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i<sentence.length();i++){
if(sentence.substring(i, i +1).equals(" ")){
arr.add(i);
}
}
return arr;
}
public int countWords(){
return getBlankPositions().size() + 1;
}
public String[] getWord(){
int numWords = countWords();
List<Integer> arrOfBlanks = getBlankPositions();
String[] arr = new String[numWords];
for (int i = 0; i<numWords; i++){
if (i ==0){
sentence.substring(i, arrOfBlanks.get(i));
arr[i] = sentence;
}else{
sentence.substring(i + arrOfBlanks.get(i), arrOfBlanks.get(i+1));
arr[i] = sentence;
}
}
return arr;
}
public static void main(String[] args) {
// TODO code application logic here
int[] arr = {3,4,5,2,4};
String sentence = "hello world I love dogs";
}
}
If i understand your objective, i think you want to count the number of words and also want to print/retrieve it. If that's the case then you don't have the complicate this that much. Use the below program.
public class Apcsa2 {
public static void main(String[] args) {
String input="hello world I love dogs";
String[] arryWords=input.split("\\s+");
//Count-Number of words
System.out.println("Count:"+arryWords.length);
//Display each word separately
for(String word:arryWords){
System.out.println(word);
}
}
}

swapping of numbers using index in java is not working

package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}

How do i call "recall" method?

Please tell me how to call recall method.
I am new in Java.
I am making a program to display prime and composite number.
package composite;
import java.util.Scanner;
public class composite {
public static void main(String[] args) {
Scanner p = new Scanner(System.in);
System.out.println("press number till you want composite number & prime numbers");
int m=p.nextInt();int g[]=new int [m+1];prime(m);
for(int k=4;k<=m;k++)
{
for(int b=2;b<k;b++){
if(k%b==0){
g[k]=k;break;
}
}
}
}
public static int prime(int m){
int e[]= new int[m+1];
for(int i=2;i<m;i++)
{
int p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
e[i]=i;
}return(m);
}
public static int recall(int m, int [] e, int [] g){
for(int a=1;a<m;a++){
System.out.println(e[a]+" "+g[a]);
}
return m;
}
}
Take a look at following and modify the variables accordingly :
Composite call_recall = new Composite();
int recall_value = recall(m,e,g);
Place the proper values as you require in place of m, e and g.

cannot be resolved to a variable java 101

Newbie code for printing a matrix:
import java.util.*;
import java.io.File;
public class Strings {
public static void main(String[] args){
Strings String1 = new Strings();
int alen =0 ,blen =0;
String a,b;
int [][] matrix = new int[alen+1][blen+1];
System.out.println("Enter String a: ");
Scanner usrip = new Scanner(System.in);
a = usrip.next();
System.out.println("Enter String b: ");
b = usrip.next();
System.out.println("Execute print method: ");
String1.printMatrix();
}//end of main
public void printMatrix(){
for(int i=0;i<alen+1;i++)
{
for(int j=0;i<blen+1;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
}// End class
Since alen , blen are declared in the class not in a mehtod I thought they were global varaibales. But looks like Its not what I think it is.
The error I get is alen cannot be resolved into a variable same for blen and matrix as well.
Same error when I try to access them like String1.alen as well.
the variables "alen" and "blen" you declared in main() are method-local, that means they are not accessible from printMatrix() method. Make them fields instead by writing:
private int alen;
private int blen;
just below the line public class Strings {
or pass them as arguments to printMatrix() method, as Christian suggested.
You cannot access alen, blen and matrix since they are not declared within the printMatrix() scope (you may want to read about scope in Java), here is one simple solution:
Pass the variables as arguments:
public void printMatrix(int alen, int blen, int[][] matrix){
...
}
and call in the main method:
String1.printMatrix(alen, blen, matrix);
Of course, that this is not necessary, you could just do:
public void printMatrix(int[][] matrix){
for(int i=0;i<matrix.length;i++)
{
for(int j=0;i<matrix[i].length;j++)
{
System.out.print(matrix[i][j]);
}
}
}
It is a bit ugly, but for a beginner, you can do the following:
public class Strings {
public int [][] matrix;
public static void main(String[] args){
Strings String1 = new Strings();
int alen =0 ,blen =0;
String a,b;
String1 = new int[alen+1][blen+1];
...
public void printMatrix(){
for(int i=0;i<matrix.length;i++)
{
for(int j=0;i<matrix[0].length;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
}// End class
this is one way among many:
public void printMatrix(int[][] matrix){
for(int i=0;i<matrix.length;i++) {
for(int j=0;i<matrix[i].length;j++) {
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix`enter code here
call it like:
String1.printMatrix(matrix);

Categories

Resources