Pergunta

O meu método locateLargest() como mostrar abaixo é um método para encontrar as coordenadas de minha maior valor na minha matriz.Eu estou tendo problemas para colocar os valores de retorno para um método toString.Eu não tenho nenhuma idéia de como formatar em o método toString.

public Location locateLargest(int[][] x){ 
    int maxValue = getMax(x);
    for (int i = 0; i < x.length; i++){
        for (int j = 0; j < x.length; j++)
            if (x[i][j] == maxValue)
                return new Location(i,j);
    }
}

Meu toString tentativa:

public String toString(){
    return "[" + i + "][" + j + "]";
}

localização código da classe:

class Location {
    private int row;
    private int column;

    Location(){}//end constructor

    Location(int row, int column){
        this.row = row;
        this.column = column;
    }//end arg constructor

    public int getRow(){
        return this.row;
    }

    public int getColumn(){
        return this.column;
    }

Aqui é a minha código do meu programa:

import java.util.Scanner;

public class LocationTest {

    public static void main(String[] args) {
        Scanner numberInput = new Scanner(System.in);
        System.out.println("Enter the number of rows and columns of the array: ");
        int row = numberInput.nextInt();
        int column = numberInput.nextInt();
        Location l1 = new Location(row, column);
        Location l2 = new Location();
        row = l1.getRow();
        column = l1.getColumn();
        int[][] array = new int[l1.getRow()][l1.getColumn()];
        System.out.println("Please enter the array elements: ");
        for (int r = 0; r < array.length; r++){
            for (int c = 0; c < array[r].length; c++){
                array[r][c] = numberInput.nextInt();
            }//end nested loop
        }//end for loop
        System.out.println(getMax(array));
        System.out.println(l1.locateLargest(array).toString());
    }

    public static int getMax(int[][] x){
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < x.length; i++){
            for (int j = 0; j < x[i].length; j++){
                if (x[i][j] > max)              
                    max = x[i][j];
            }
        }
        return max;
    }

    public Location locateLargest(int[][] x){ 
        int maxValue = getMax(x);
        for (int i = 0; i < x.length; i++){
            for (int j = 0; j < x.length; j++)
                if (x[i][j] == maxValue)
                    return new Location(i,j);
        }
        return null;
    }
}

class Location {
    private int row;
    private int column;

    Location(){}//end constructor
    Location(int row, int column){
        this.row = row;
        this.column = column;
    }//end arg constructor

    public int getRow(){
        return this.row;
    }

    public int getColumn(){
        return this.column;
    }

    public String toString(){
        return "[" + row + "][" + column + "]";
    }
}
Foi útil?

Solução

Se o Local é uma classe definida a si mesmo, você deve implementar a função toString (), bem

class Location{
    int locationX,locationY;    

    public Location(int x,int y){
        locationX = x;
        locationY = y;
    }

    public String toString(){
        return locationX+","+locationY;
    }
}

Outras dicas

Um método toString tem o cabeçalho

public String toString()

então tudo que você precisa fazer é criar um método com o cabeçalho que retorna uma Seqüência de caracteres.

Sua pergunta é muito vaga, como alguém observou acima, e a Localização não é um padrão de biblioteca de classe, então eu não posso lhe dar nada em especial, mas algo como

public String toString() {
    return "(" + x + ", " + y + ")";
}

pode ser próximo ao que você está indo para se você quer um toString para representar um ponto.

O que você precisa para converter para String?De qualquer maneira, tudo o que você fizer, adicione o seguinte ao final:

.toString();

Você pode fazer uma variável de Seqüência de caracteres e devolvê-lo:

StringVariable = <object>.toString();

ou apenas imprimi-lo ou fazer qualquer outra coisa

System.out.println(<object>.toString());

Espero que ajudaram.Se ele não me dizer sobre isso nos comentários!

a maneira mais seria colocar em sua classe:

public String toString(){
        return String.format("[%i][%i]",row,column);
    }

im não tem certeza se isso ajuda, mas talvez, talvez, os códigos abaixo ajuda

  return new Location(i,j);
 String toStringI = Integer.toString(i); 
    String ToStringj = integer.toString(j);

ou usando Seqüência de caracteres.valueOf(myInteger);

A classe "Nome:Local" é definido para inteiros se você está tentando mostrar na janela de saída ou de tentar isso?

System.out.println("",i,"",j);

que seja ;p

Você shoulrd uso row column

public String toString(){
    return "[" + row + "][" + column + "]";
}

Você não pode usar i j porque não i j existe no Location.

public String toString(){
    return "[" + i + "][" + j + "]";
}

Enquanto este (abaixo) é o seu construtor e não o que você tinha antes com xLocation e yLocation, você deve ser fino.

Location(int row, int column){
    this.row = row;
    this.column = column;
}//end arg constructor
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top