How to pass a string to two whole types?

Asked

Viewed 106 times

-1

I’m doing an exercise where the program receives as input a "String" with two values , and in the end I need to put these two values into integer variables and carry out the sum of them. I researched and read about the Bufferreader and the Stringtokenizer. My question is how to implement this, I need to make a Bufferreader to read the String that will be inserted and the Stringtokenizer performs this separation of my string into two? And how I turn that string into integers?

Entrada: "11 8"
Saida : 19

Code I’ve made so far:

public class MinhaPrimeiraClasse {
 public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String valor = " ";
    
    System.out.println("Insira os valores:");
    valor = br.nextLine();
    Integer a = 0;
    Integer b = 0;
    Integer c = a + b;
    
    a = Integer.parseInt(br.readLine());
    b = Integer.parseInt(br.readLine());

    System.out.println(" "+c);

 }
}

I don’t know how to separate the string and play the two values in the variables a and b

3 answers

2

You can use the class java.util.Scanner which is a plain text scanner that can parse and primitive strings and types using regular expressions. The instance of Scanner divides your input into tokens using a delimiter, which by default corresponds to blank spaces. The resulting tokens can then be converted into values of different types.

import java.util.*;

class Main {
  //Método para leitura de um inteiro de um Scanner.
  private static int lerInteiro(Scanner sc) throws IllegalArgumentException {
    //Verifica se o próximo token a ser lido é um inteiro.
    if (sc.hasNextInt()) {
      return sc.nextInt();                       //Se for o próximo token um inteiro o retorna.
    }
    //Se próximo token não for um inteiro atira uma exceção. 
    throw new IllegalArgumentException(sc.next() + " valor inválido."); 
  }

  public static void main(String[] args) {
    int a, b;                                    //Declara 'a' e 'b'.
    Scanner sc = new Scanner(System.in);         //Inicializa uma instancia de Scanner em System.in.
    System.out.println("Insira os valores:");
    //Abre um bloco de tratamento de exceções.
    try {
      a = lerInteiro(sc);                         //Lê um inteiro em 'a'.
      b = lerInteiro(sc);                         //Lê um inteiro em 'b'.
      System.out.println(a + b);                  //Imprime a soma de 'a' e 'b'.
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());         //Caso haja uma exceção de leitura de um dos valores imprime a mensagem de erro.
    }
  }
}

Test the code on Repl.it

The method Scanner.hasNextInt() returns true if the next token in the input can be interpreted as a value int.
The method Scanner.nextInt() returns next entry token as a int.
The method Scanner.next() returns next entry token as a string.
The method Scanner.close() closes the instance of Scanner. Before using Scanner.close() see the guidelines in Build error: "Resource Leak" when using Scanner.

Read also Java Tutorial Exceptions.

  • 1

    In the specific case of System.in, does not need (and would say not need) to close it: https://answall.com/a/380458/112052

  • @hkotsubo. I did not know that, for me had to close in all cases.

0

Good in a simple way what I understood is that Voce needs to receive two values that turn form String convert them into Integer and add them up.

You can do the following

public static void main(String[] args) {
        Integer valor1 = Integer.parseInt(args[0]);
        Integer valor2 = Integer.parseInt(args[1]);
        System.out.println("valor1: " + valor1);
        System.out.println("valor2: " + valor2);
        System.out.println("Soma dos Valores: " + (valor1 + valor2));
    }

args is called in the execution of the Java program, it is a String Array, so it would only be necessary to talk your items to String for an Integer in this way for example

Integer valor1 = Integer.parseInt(args[0]);

and when you run the Voce program you will pass the values for example

java Programa.class valor1 valor2

0


I don’t understand why you’re adding a with b before even assigning user input values to these variables, but to separate a string just use the method split passing the separator as parameter.

Then you would

System.out.println("Insira os valores: ");
String entrada = br.nextLine();
String[] valores = entrada.split(" ");

int a = Integer.parseInt(valores[0]);
int b = Integer.parseInt(valores[1]);
int c = a + b;

This considering that the user will not enter an invalid value.

  • Actually I ended up not seeing this error in the sum line, but it worked, I only changed the br.nextLine() by br.readline(); Doubt solved, can close the topic

Browser other questions tagged

You are not signed in. Login or sign up in order to post.