how to have multiply constructors in one class? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I want to have two constructors in one class but I can't. I know it is possible but I can't find my mistake.
public static class Matrix{
int [][] matrix;
int row;
int column;
String matrixName;
Matrix (String [] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int [row][column];
initialize(input);
}
Matrix (Matrix A, char ch) {
if (ch == 'T'){
column = A.row;
row = A.column;
}
else{
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
}
the second Matrix can't be defined as a constructor.

There is no problem with the second constructor. The problem is with the first line of the declaration which is public static class Matrix. Note that you can not use static modifier here. Only public, abstract and final are allowed.
After this correction, you can test your class as follows:
class Matrix {
int[][] matrix;
int row;
int column;
String matrixName;
Matrix(String[] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int[row][column];
// initialize(input);
System.out.println("First");
}
Matrix(Matrix A, char ch) {
if (ch == 'T') {
column = A.row;
row = A.column;
} else {
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
System.out.println("Second");
}
}
public class Main {
public static void main(String[] args) {
Matrix m1 = new Matrix(new String[] { "a", "b" }, "Hello");
Matrix m2 = new Matrix(m1, 'X');
}
}
Output:
First
Second

Is it nested class in another class? Because class can be static only when it is nested in another class like this:
public class Matrix {
public static class NestedClass {
int number;
String string;
public NestedClass(NestedClass A, String string) {
this.number = A.number;
this.string = string;
}
public NestedClass(NestedClass A) {
this.string = A.string;
}
}
}
Class Matrix cannot be static, only final or abstract.

Related

array in constructor keeps returning as null? [duplicate]

This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
Closed 3 months ago.
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
int[] pascal;
char[] Larray;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
im trying to do this code but pascal, keeps returning as null, when I declare it outside the constructor;
ive also tried this...
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
and I get this error
sierpinski.java:8: error: cannot find symbol
System.out.println(String.valueOf(s1.pascal));
^
symbol: variable pascal
location: variable s1 of type sierpinski
1 error
error: compilation failed
saying it cannot find symbol, any solutions and does anyone know how to fix this??
thanks
tried declaring the variable at the top, but I have no clue how to get this to work, any ideas?
Constructors are essentially methods.
sierpinski(int row) { // this is a constructor
this.row = row; // this sets a field.
int[] pascal = new int[row+1]; // this creates a new local variable
// constructor ends, and with it, all local variables GO AWAY
}
You want to declare a field. You already have one (row), and you already set it (this.row = row). If you want pascal to still exist when the constructor ends, it needs to be a field and not a local:
public Sierpinski {
private int row;
private int[] pascal;
public Sierpinski(int row) {
this.row = row;
this.pascal = new int[row];
}
}

Word object changing after pushing onto stack Java

while(!paths.isEmpty()){
BoggleSearchState2 path = paths.pop();
if(dictionary.contains(path.getWord()) && !foundWords.contains(path.getWord())){
foundWords.add(path.getWord());
}
int[][] grid = path.getGrid();
int row = path.getRow();
int column = path.getColumn();
Letter[][] game = path.getGame();
if(row < (grid.length-1) && grid[row+1][column] == 0) {
paths.push(new BoggleSearchState2(path.getWordWord(), game[(row+1)][column], game));
}
}
My BoggleSearchState2 constructor is overloaded like this:
public BoggleSearchState2(Letter l, Letter[][] gameIn) {
game = gameIn;
word = new Word(l);
grid = initialGrid(l);
row = l.getPoint().y;
column = l.getPoint().x;
stringWord = wordToString(word);
}
public BoggleSearchState2(Word wordIn, Letter l, Letter[][] gameIn){
game = gameIn;
word = new Word(wordIn.getLetters());
word.addLetter(l);
grid = genGrid(word, game);
row = l.getPoint().y;
column = l.getPoint().x;
stringWord = wordToString(word);
}
With my class variables like this:
public class BoggleSearchState2 {
private Word word;
private Letter[][] game;
private int[][] grid;
private String stringWord;
private int row, column;
The problem i am having is that after i push the new BoggleSS2, my path.word changes and adds another letter object. i do not know how this is happening. can anyone tell me why?
public class Word {
private ArrayList<Letter> word;
public Word(Letter l) {
word = new ArrayList<Letter>();
word.add(l);
}
public Word(ArrayList<Letter> listLetters, Letter l){
word = listLetters;
word.add(l);
}
public Word(ArrayList<Letter> letters) {
word = letters;
}

Array of strings from array of pairs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there anyway I could return an array of strings from an array of pairs? I'm guessing it's something to do with hashmap since two values are involved. Any simple example with some explanation would help :)
As pointed out by #dasblinkenlight, if the input is (y,3),(t,2) and I want the output as "yPP","tP" where the string should have the length of the numerical value given. and so after taking the character, the rest of the length is to be filled by P.
Suppose I've got the static method,
public static Line[] get(Couple[] temp)
I need to complete it so that my main method would produce the following result:
get (new Couple[]{new Couple(’e’,4), new Couple(’n’,2)})
should return the array of Strings
{"ePPP", "nP"}
Hope this helps :)
class Pair{
public Pair(String st1,String st2){
string1=str;
string2=str;
}
private String string1;
private String string2;
// + getters and maybe setters for strings;
}
Later on create simple Pair[] and do whatever you want
With a Pair class implemented as
class Pair {
private final String s;
private final int i;
public Pair(String s, int i){
this.s = s;
this.i = i;
}
public String getS() {
return s;
}
public int getI() {
return i;
}
}
Initialize the Pair[] and invoke a converter method as
Pair[] pairArr = new Pair[2];
pairArr[0] = new Pair("Y", 3);
pairArr[1] = new Pair("T", 2);
System.out.println(Arrays.toString(convertPairsToStrArray(pairArr, "P")));
Output :
[YPP, TP]
Here's a sample converter implementation:
private static String[] convertPairsToStrArray(Pair[] pairArr, String padStr) {
String[] strArr = null;
if (pairArr != null) {
strArr = new String[pairArr.length];
for (int i = 0; i < pairArr.length; i++) {
String s = pairArr[i].getS();
StringBuilder sb = new StringBuilder();
if (s != null) {
sb.append(s);
int j = 0;
if ((j = pairArr[i].getI() - s.length()) > 0) {
while (j-- > 0) {
sb.append(padStr);
}
}
}
strArr[i] = sb.toString();
}
}
return strArr;
}
Like many things, the question contains the answer.
Create a class to hold the pairs. Add a method, to that class, to produce the desired output. Here is some code:
Pairzor.java:
public class Pairzor
{
private final static char FILL_CHARACTER = 'P';
private final char theChar;
private final int theCount;
public Pairzor(
final char newChar,
final int newCount)
{
theChar = newChar;
theCount = newCount;
}
public final String blammy()
{
StringBuilder buffer = new StringBuilder();
buffer.append(theChar);
for (int count = 1; count < theCount; ++count)
{
buffer.append(FILL_CHARACTER);
}
return buffer.toString();
}
}
Main.java
public class Main
{
/**
* #param args
*/
public static void main(String[] args)
{
Pairzor one = new Pairzor('y', 3);
Pairzor two = new Pairzor('t', 2);
System.out.println(one.blammy());
System.out.println(two.blammy());
}
}

Why is there an NullPointerException?

I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.

Help me with this Java code

Question:
matrix m1 = new matrix(); // should produce a matrix of 3*3
matrix m2 = new matrix(5,4); //5*4
matrix m3 = new matrix(m2); //5*4
What should be there in the copy constructor to make a new matrix m3 of the same order as of m2?
public class matrix {
int a[ ][ ];
matrix(){
a = new int[3][3];
}
matrix(int x, int y){
a= new int [x][y];
}
matrix (matrix b1){
//how to use value of x and y here....
}
void show(){
System.out.println(a.length);
for(int i=0;i<a.length;i++){
System.out.print(a[i].length);
}
}
}
public class matrixtest {
public static void main(String [ ] args){
matrix a = new matrix();
matrix b = new matrix(5,4);
matrix c = new matrix (b);
a.show();
b.show();
c.show();
}
}
NOTE: You can not use any extra instance variable except the array a.
Accepted answer: #Chankey: this(b1.a.length,b1.a[0].length); – John
Store the number of rows, and the number of columns in the matrix class, and create getters for them.
public class Matrix {
int[][] a;
int rowNum;
int colNum;
//...
public Matrix(Matrix b) {
a=new int[b.getRowNum()][b.getColNum()];
this.rowNum = b.getRowNum();
this.colNum = b.getColNum();
}
public int getRowNum() {
return this.rowNum;
}
}
You need to get the size of the passed b1 matrix
int x = b1.length;
int y = b1[0].lenght;
and can then use it to construct the final array.
a= new int [x][y];
Use
a =new int[b1.a.length][b1.a[0].length];
But it is not recommended .
you should have some get method , which return
matrix dimension.
This is homework, so I'll give you a hint:
How would you get the lengths of the 2 dimensional matrix (a[][]) of b1? proper methods in the matrix class will help - how would you implement those (getX, getY)?
Also, it is better to redirect the constructors to the most detailed one, for example:
matrix(){
this(3,3); // call the constructor below with parameters 3,3
}
matrix(int x, int y){
a= new int [x][y];
}
This can be the most probable answer without using any other instance variable other then the array itself:
import java.io.*;
class matrix
{
private int arr[][];
public matrix() //Default Constructor
{
this(3,3);
}
public matrix(int r,int c) //Parameterized Constructor
{
arr=new int[r][c];
read();
}
public matrix(matrix m) //Copy Constructor
{
System.out.println("Fetching array...");
int r,c;
r=m.arr.length;
c=m.arr[0].length;
arr=new int [r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=m.arr[i][j];
}
}
}
public void read()
{
int i,j,r,c;
r=arr.length;
c=arr[0].length;
Console con=System.console();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
arr[i][j]=Integer.parseInt(con.readLine());
}
}
}
public void show()
{
int i,j;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr[0].length;j++)
{
System.out.print(" "+arr[i][j]);
}
System.out.println();
}
}
}

Categories

Resources