Friday, July 31, 2009

Input in Java?

Hi there,





i am new to java and i am trying to do a program that prompts user to input a value and my program reads the value and display it out and do a if statement.


if(value%26lt;10)


System.out.println("correct");





how can i obtain value that the user input..





I know how to do it in C++.


cout%26lt;%26lt;"enter values";


cin%26gt;%26gt;values;


cout%26lt;%26lt;values;





however, how do i do it in java? i am new to java..and i was reading online tips, but i still don't get it. thanks.

Input in Java?
Hello! You need to implement the EasyReader class. First, you need to declare a variable "a". You also have to prompt the user to put in a value. Then, you will read the user's input. That is when your if/else statement will come. It should look like:





int a=0;


EasyReader input = new EasyReader();


System.out.println("Type in a number");


a=input.readInt();


if(a%26lt;10)


System.out.println("Correct");


else


System.out.println("Incorrect");





I hope you find that helpful!
Reply:Accepting user input via the command line is a bit more complex than in C. In C, accepting user input would look something like:





cout %26lt;%26lt; "Enter your namen";


cin %26gt;%26gt; Name;


cout %26lt;%26lt; "Thank you" %26lt;%26lt; Name;





In Java, however, we use a System.in. Easy enough, review this example:





import java.io.*;





public class ReadString {





public static void main (String[] args) {





// prompt the user to enter their name


System.out.print("Please enter your name: ");





// open up an input


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));





String yourName = null;





// read the input from the command-line; need to use try and catch with the readLine() method


try {


yourName = br.readLine();


} catch (IOException ioe) {


System.out.println("IO error trying to read your name!");


System.exit(1);


}





System.out.println("Thanks for the name, " + yourName);





}





}





First we read the user's input by passing the System.in object to the InputStreamReader, and then into the BufferedReader. The BufferedReader class gives us the readLine() method, and applies buffering to the input character input stream. Notice that the readLine() method can thrown an IOException error, so we have to enclose the statement in a try/catch statement.


No comments:

Post a Comment