Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Erro na hora de formatar

package br.com.alura.java.io.teste;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.util.Scanner;

public class TesteScanner {

    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(new File("contas.csv"));

        while (scanner.hasNextLine()) {
            String linha = scanner.nextLine();
            System.out.println(linha);    

            Scanner linhaScanner = new Scanner(linha);
            linhaScanner.useDelimiter(",");

            String conta = linhaScanner.next();
            int agencia = linhaScanner.nextInt();
            int numero = linhaScanner.nextInt();
            String titular = linhaScanner.next();
            double saldo = linhaScanner.nextDouble();

            String valorFormatado = String.format(new Locale("pt","BR"), "%s, %04d-%04d, %10s: %f%n",
                    conta, agencia, numero, titular, saldo);

            System.out.println(valorFormatado);

            linhaScanner.close();
        }
        scanner.close();
    }

}

Não formata o double aparecendo somente Exception in thread "main" java.util.InputMismatchException

1 resposta
solução!

No seu código faltou incluir:

linhaScanner.useLocale(Locale.US);

Código correto:

package br.com.alura.java.io.teste;

import java.io.File;
import java.util.Locale;
import java.util.Scanner;

public class TesteLeitura2 {

    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(new File("contas.csv"), "UTF-8");
        while(scanner.hasNextLine()) {
            String linha = scanner.nextLine();
            //System.out.println(linha);

            Scanner linhaScanner = new Scanner(linha);
            linhaScanner.useLocale(Locale.US);
            linhaScanner.useDelimiter(",");

            String tipoConta = linhaScanner.next();
            int agencia = linhaScanner.nextInt();
            int numero = linhaScanner.nextInt();
            String titular = linhaScanner.next();
            double saldo = linhaScanner.nextDouble();

            System.out.format(new Locale("pt","BR"), "%s - %04d-%08d, %20s: %08.2f %n", 
                    tipoConta, agencia, numero, titular, saldo );;

            linhaScanner.close();

//            String[] valores = linha.split(",");
//            System.out.println(valores[3]);
        }
        scanner.close();
    }
}

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software