Jump to content

Ler matriz de ficheiro


Guest darkangel_13

Recommended Posts

Posted

Bom dia , estou a tentar ler uma matriz cuja primeira linha tenho o numero de linhas e numero de colunas .

5 5
1 2 5 3 2
4 3 2 4 2
5 6 2 3 1
1 2 2 3 4
1 3 4 5 2

Tentei com um ciclo while só que disse-me java.util.NoSuchElementException ou seja apaguei o codigo e tou a tentar fazer de novo.

Então eu pensei nisto , dois ciclos for para me construirem a matriz ... só que primeiro tenho que conseguir separar o primeiro valor 5 e mete-lo numa variavel e o segundo noutra variavel, como faria isso com tokens ? iria ajudar ?

cumps

Posted

Dá uma vista de olhos nisto:

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Vê também o método nextInt() desse objeto.

"[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31

Life is a genetically transmitted disease, induced by sex, with death rate of 100%.

Posted

Boas obrigado pela resposta, eu estava a usar inicialmente agora tenho estado de novo a tentar e nada...

int x= leitor.nextInt();
int y= leitor.nextInt();
int[][]matriz=new int[x][y];
if( leitor.hasNextInt()==false)
System.out.println("ficheiro nao contem matriz");
else{
for(int i =0;i<x;i++){
for(int j=0;j<y;j++){
 leitor.nextLine();
 matriz[i][j]=leitor.nextInt();
}
}

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at RunMatriz.main(RunMatriz.java:15)
Posted

como é que estás a instanciar esse... "leitor"?

E, já agora, aonde é que está a linha 15?

"[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31

Life is a genetically transmitted disease, induced by sex, with death rate of 100%.

Posted (edited)
import java.util.Scanner;
import java.io.*;
public class RunMatriz{
public static void main(String[] args)throws IOException{
Scanner leitor=new Scanner(new FileReader("ficheiro.txt"));
int x= leitor.nextInt();
int y= leitor.nextInt();
int[][]matriz=new int[x][y];
if( leitor.hasNextInt()==false)
System.out.println("ficheiro nao contem matriz");
else{
for(int i =0;i<x;i++){
for(int j=0;j<y;j++){
 leitor.nextLine();
 matriz[i][j]=leitor.nextInt(); // linha 15
}
}

ups nao colei tudo

Edited by darkangel_13
Posted

Mostra o que tens escrito nesse "ficheiro.txt", sff.

"[Os jovens da actual geração]não lêem porque não envolve um telecomando que dê para mirar e atirar, não falam porque a trapalhice é rainha e o calão é rei" autor: thoga31

Life is a genetically transmitted disease, induced by sex, with death rate of 100%.

Posted

Mostra o que tens escrito nesse "ficheiro.txt", sff.

Obg pela resposta..

5 5

1 2 5 3 2

4 3 2 4 2

5 6 2 3 1

1 2 2 3 4

1 3 4 5 2

Posted

Já tirei e já le a matriz mas com um problema o x e o y ficam com o primeiro valor apenas

Posted

não sei o que andas a fazer mas se fizeste o que disseste (retirar a linha) o código funciona

import java.util.Scanner;
import java.io.*;

public class Main
{
 public static void main(String[] args) throws IOException
 {
   Scanner leitor = new Scanner(new FileReader("ficheiro.txt"));

   int x = leitor.nextInt();
   int y = leitor.nextInt();

   int[][] matriz = new int[x][y];

   if(!leitor.hasNextInt())
     System.out.println("ficheiro nao contem matriz");
   else
   {
     for(int i =0;i<x;i++)
     {
       for(int j=0;j<y;j++)
       {
//          leitor.nextLine();
         matriz[i][j] = leitor.nextInt();
       }
     }

     System.out.println("Matrix : " + Integer.toString(x) + "x" + Integer.toString(y));
     for(int i =0;i<x;i++)
     {
       for(int j=0;j<y;j++)
       {
         System.out.print(Integer.toString(matriz[i][j]) + " ");
       }
       System.out.println();
     }
   }
 }
}
IRC : sim, é algo que ainda existe >> #p@p
Posted

Obrigado pela ajuda! Tentei com este input

3 5

6 9 1 3 4

4 5 4 2 1

2 4 6 8 0

E vejo que apenas armazenou isto

6 9 1

4 5 4

2 4 6

Posted

Criei este ciclo

for(int h =0;h<matriz.length;h++){
for(int z =0;z<matriz.length;z++){
System.out.print(matriz[h][z]);}
System.out.println("");
Posted
for(int h =0;h<matriz.length;h++){
   for(int z =0;z<matriz[h].length;z++){

Obrigado vi agora mesmo o erro!

Posted (edited)

Aproveitando o topico .

Estou a tentar criar um metodo que me vai subtrair as linhas da matriz por uma dessa mesma matriz..

Imaginando que a linha é a primeira

Isto:

6 9 1 3 4

4 5 4 2 1

2 4 6 8 0

Fica :

6 9 1 3 4 // mantendo a linha que tem os valores para a subtraçao intocavel

2 4 3 1 3

4 5 5 5 1

Tentei agora fazer isto

int[][] subtraiLinha(int[][] matriz, int linha){
int [][]subtraida=new int[matriz.length][matriz[0].length];
for(int i=0;i<matriz.length;i++){
 for(int j=0;j<m.length;j++){
  if(i==linha){
   matriz[linha][j]=matriz[j];}
  else{

return subtraida;
Edited by brunoais
geshi

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.