Java equivalent of cin

G

Gregory W. Ernest

I am new to Java programming and I was wondering if anyone can tell me the
java equivalent to a cin>>...; that is normally used in c++. I want to get
user input and automatically assign it to a variable. So in other words what
would be the equivant java statement of this c++ statement:

1: cout<<"Enter a number.";
2: cin>>x; //This is what I really want to know. I already know the java
equivalent of the first statement.
 
H

Harish

yes System.out is the standard output of a java program.
and System.in is the standard input.
so try System.in.read...
 
M

moongate

The main difference being that System.in belongs to class InputStream,
which does not provide functionaly as rich as C++'s "cin"; instead, it
focuses on low-level, byte-oriented input operations. In most cases,
you will want to wrap System.in with filter objects that augment its
functionality (stream wrapping basically works as in C++). A common
wrapping would be something like

BufferedReader dis = new BufferedReader(new
InputStreamReader(System.in))

where BufferedReader augmented functionality allows you, for example,
to read character input line by line:

String line = bin.readLine();

Look for other wrappings based on your specific needs. You might want
to take a look at basic principles of Java I/O (e.g., the difference
between "Reader/Writer" and "Stream" classes) in a tutorial or a book.
MC
 
Joined
Aug 3, 2008
Messages
1
Reaction score
0
A Java Cin like class

import java.io.*;


/**
* @author gstkein
*
*/
public class Cin {

public static int Int(){

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int intInput=-1;
boolean invalido = true;

while (invalido) {
invalido=false;
try {
intInput = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
invalido=true;
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
invalido=true;
}
}
return intInput;
}

public static String String() {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input="";

try {
input = (br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return input;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.print("Type your name: ");
String name = Cin.String();
System.out.print("Type a number: ");
int number = Cin.Int();
System.out.println(name);
System.out.println(number);



}

}
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top