I'm trying to read an int with BufferedReader
. I know i have a mismatch with the type (string, int) but i not sure what i need to change about the code to make it work.
I know how to use it for string reading and printing but no for int and use some operators
import java.io.*;
public class tmetodoI {
public static void main(String[] args) {
BufferedReader dataIn = new BufferedReader
(new InputStreamReader(System.in));
String num = "";
System.out.print("Ingrese un valor entero para determinar si es multiplo de 6");
try {
num = dataIn.readLine();
} catch(IOException e) {
System.out.print("Error!");
}
if (num%6>0)
}
}
CodePudding user response:
The BufferedReader class doesn’t provide any direct method to read an integer from the user you need to rely on the readLine()
method to read integers. i.e. Initially you need to read the integers in string format.
The parseInt()
method of the Integer class accepts a String value, parses it as a signed decimal integer, and returns it.
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
int value = Integer.parseInt(reader.readLine());
You can also use the Scanner class
which provides a predefined method to take integer input
Scanner myInput = new Scanner( System.in );
int value=myInput.nextInt();
CodePudding user response:
You convert your string into int using Integer.parseInt(num);
To convert into other primitive data types have a look at
CodePudding user response:
you can use Integer.parseInt(String)
to convert String
to int
, use following code:
public static void main(String[] args) {
BufferedReader dataIn = new BufferedReader
(new InputStreamReader(System.in));
String num = "";
System.out.print("Ingrese un valor entero para determinar si es multiplo de 6");
try {
num = dataIn.readLine();
} catch(IOException e) {
System.out.print("Error!");
}
if (Integer.parseInt(num)%6 > 0) {
System.out.println("inside condition");
} else {
System.out.println("out of the condition");
}
}
CodePudding user response:
You can use Integer.parseInt(String s)
method to convert String to Integer.
Here is the complete code of the inside of the main function:
BufferedReader dataIn = new BufferedReader
(new InputStreamReader(System.in));
String num = "";
Integer number = null;
System.out.print("Ingrese un valor entero para determinar si es multiplo de 6");
try {
num = dataIn.readLine();
number = Integer.parseInt(num);
} catch(IOException e) {
System.out.print("Error!");
}
if (number%6>0) {
System.out.println("number % 6 > 0");
} else {
System.out.println(":(");
}