taking integer input in java - java

I am actually new to java programming and am finding it difficult to take integer input and storing it in variables...i would like it if someone could tell me how to do it or provide with an example like adding two numbers given by the user..

Here's my entry, complete with fairly robust error handling and resource management:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Simple demonstration of a reader
*
* #author jasonmp85
*
*/
public class ReaderClass {
/**
* Reads two integers from standard in and prints their sum
*
* #param args
* unused
*/
public static void main(String[] args) {
// System.in is standard in. It's an InputStream, which means
// the methods on it all deal with reading bytes. We want
// to read characters, so we'll wrap it in an
// InputStreamReader, which can read characters into a buffer
InputStreamReader isReader = new InputStreamReader(System.in);
// but even that's not good enough. BufferedReader will
// buffer the input so we can read line-by-line, freeing
// us from manually getting each character and having
// to deal with things like backspace, etc.
// It wraps our InputStreamReader
BufferedReader reader = new BufferedReader(isReader);
try {
System.out.println("Please enter a number:");
int firstInt = readInt(reader);
System.out.println("Please enter a second number:");
int secondInt = readInt(reader);
// printf uses a format string to print values
System.out.printf("%d + %d = %d",
firstInt, secondInt, firstInt + secondInt);
} catch (IOException ioe) {
// IOException is thrown if a reader error occurs
System.err.println("An error occurred reading from the reader, "
+ ioe);
// exit with a non-zero status to signal failure
System.exit(-1);
} finally {
try {
// the finally block gives us a place to ensure that
// we clean up all our resources, namely our reader
reader.close();
} catch (IOException ioe) {
// but even that might throw an error
System.err.println("An error occurred closing the reader, "
+ ioe);
System.exit(-1);
}
}
}
private static int readInt(BufferedReader reader) throws IOException {
while (true) {
try {
// Integer.parseInt turns a string into an int
return Integer.parseInt(reader.readLine());
} catch (NumberFormatException nfe) {
// but it throws an exception if the String doesn't look
// like any integer it recognizes
System.out.println("That's not a number! Try again.");
}
}
}
}

java.util.Scanner is the best choice for this task.
From the documentation:
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Two lines are all that you need to read an int. Do not underestimate how powerful Scanner is, though. For example, the following code will keep prompting for a number until one is given:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
while (!sc.hasNextInt()) {
System.out.println("A number, please?");
sc.next(); // discard next token, which isn't a valid int
}
int num = sc.nextInt();
System.out.println("Thank you! I received " + num);
That's all you have to write, and thanks to hasNextInt() you won't have to worry about any Integer.parseInt and NumberFormatException at all.
See also
Java Tutorials/Essential Classes/Basic I/O/Scanning and Formatting
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
How to use Scanner to accept only valid int as input
Other examples
A Scanner can use as its source, among other things, a java.io.File, or a plain String.
Here's an example of using Scanner to tokenize a String and parse into numbers all at once:
Scanner sc = new Scanner("1,2,3,4").useDelimiter(",");
int sum = 0;
while (sc.hasNextInt()) {
sum += sc.nextInt();
}
System.out.println("Sum is " + sum); // prints "Sum is 10"
Here's a slightly more advanced use, using regular expressions:
Scanner sc = new Scanner("OhMyGoodnessHowAreYou?").useDelimiter("(?=[A-Z])");
while (sc.hasNext()) {
System.out.println(sc.next());
} // prints "Oh", "My", "Goodness", "How", "Are", "You?"
As you can see, Scanner is quite powerful! You should prefer it to StringTokenizer, which is now a legacy class.
See also
Java Tutorials/Essential Classes/Regular expressions
regular-expressions.info/Tutorial
Related questions
Scanner vs. StringTokenizer vs. String.Split

you mean input from user
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = s.nextInt();
//process the number

If you are talking about those parameters from the console input, or any other String parameters, use static Integer#parseInt() method to transform them to Integer.

Related

How can I use a scanner to read in integers, more specifically an integer describing a matrix dimension followed by the integers in the matrix?

I can't get my scanner to read in the integer from a text file.
The file looks something like this (a matrix size followed by a matrix)
3
0 1 1
1 1 1
1 0 0
These two methods belong to ReadMatrix
public void openFile() {
try {
scanner = new Scanner(System.in); // create a scanner object
System.out.println("File to read: ");
fileName = scanner.nextLine(); // get name of file
System.out.println("File " + fileName + " is opened.");
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
System.out.println("can't find the funky file");
}
}
public int readInteger() {
sc = new Scanner(System.in);
// while(sc.hasNextInt()){
// sc.nextLine();
anInt = sc.nextInt();
System.out.println("Trying to read integerrrrrr help");
// }
return anInt;
}
Here are 2 classes
public class MainMethodHere {
public static void main(String[] args) {
// TODO Auto-generated method stub
RunMainMethod running = new RunMainMethod();
}
}
public class RunMainMethod {
ReadMatrix a = new ReadMatrix();
public RunMainMethod(){
a.openFile();
a.createFile();
System.out.println("just createdFile"); //<--- this is where the program ends
a.readInteger();
System.out.println("just readInteger");
a.helpMeWrite();
System.out.println("Just write sample ");
a.closeResources();
}
}
Writing to the file works fine, but I can't get the program to read the given text file to start the manipulation.
I tried finding the solutions in a few SO posts: how to read Integer from a text file in Java
Reading numbers from a .txt file into a 2d array and print it on console
How to read integer values from text file
I also tried ReadFile() and WriteFile(), but when I try to track my code via printing into the console, my simple integers shows up as different values. Is that something related to bytes? So I try reverting back to using a scanner, but somehow it's not working. Please let me know if I should clarify something further. I am new to coding and SO.

what are the fast ways to take input in java?

In Java i take Input using standard Scanner and BufferedReader Classes like:
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
or
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
but taking input like this takes a lot of running time. I would like to know the faster way to take input. Thanks in advance
Edit: I have seen top java coders like uwi who take input in a very different way. They kinda create their own reader class. I dont get it that how their program becomes fast in runtime.
In the article below, the author discusses three different ways for reading input from the user in the console. Each way is fairly easy to use and also has its own advantages and drawbacks.
The below mechanisms are discussed and examples are provided.
There is also a pros and cons section as well.
Link:
http://www.codejava.net/java-se/file-io/3-ways-for-reading-input-from-the-user-in-the-console
Link:
Most Efficient Way of Taking User Input in Java
Options:
Scanner Class->
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt();
DataInputStream->
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
BufferedReader ->
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Your name is: " + name);
Console->
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Quote from dejavu:
"BufferedReader is a lot faster than Scanner because it buffers the character so you don't have to access the file each time you want to read a char from it.
Scanner are of particular use such as reading primitive data type directly and is also used for regular expressions.
I have used Scanner and BufferedReader both and BufferedReader gives significant fast performance. You can test it yourself too."
from:which to choose buffered reader or scanner from performance point of view
If you want a fast way to input via stdin (and, if I understand you correctly, you want a fast way to repeatedly feed inputs to your programs), your best bet is to pipe or redirect canned responses e.g.
$ java MyReadingClass < mycannedinput.txt
so you can build your class to take interactive input via stdin, and then use a simple shell redirection to feed in canned input such that you don't have to retype it each time.
The Fastest way to take userinput in java in particularly Competitive coding is to make own FastReader class by using bufferedReader and StringTokenizer.
This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of user defined methods for less typing and therefore a faster input altogether. This gets accepted with a time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough to meet the needs of most of the question in competitive coding.
Implementation :
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
In Main File :
public static void main(String[] args)
{
FastReader s=new FastReader();
int n = s.nextInt();
int k = s.nextInt();
int count = 0;
while (n-- > 0)
{
int x = s.nextInt();
if (x%k == 0)
count++;
}
System.out.println(count);
}
Source Link : https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
This is repeated question and an optimized way to read and write data in java can be found at the below link.
https://stackoverflow.com/a/49957378/5076337
These classes are very useful in reading inputs and writing outputs in programming contests.

Reading in a file and processing data

I am a noobie at programming and I can't seem to figure out what to do.
I am to write a Java program that reads in any number of lines from a file and generate a report with:
the count of the number of values read
the total sum
the average score (to 2 decimal places)
the maximum value along with the corresponding name.
the minimum value along with the corresponding name.
The input file looks like this:
55527 levaaj01
57508 levaaj02
58537 schrsd01
59552 waterj01
60552 boersm01
61552 kercvj01
62552 buttkp02
64552 duncdj01
65552 beingm01
I program runs fine, but when I add in
score = input.nextInt(); and
player = input.next();
The program stops working and the keyboard input seems to stop working for the filename.
I am trying to read each line with the int and name separately so that I can process the data and complete my assignment. I don't really know what to do next.
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
private Scanner input = new Scanner(System.in);
private static int fileRead = 0;
private String fileName = "";
private int count = 0;
private int score = 0;
private String player = "";
public static void main(String[] args) {
Program1 p1 = new Program1();
p1.getFirstDecision();
p1.readIn();
}
public void getFirstDecision() { //*************************************
System.out.println("What is the name of the input file?");
fileName = input.nextLine(); // gcgc_dat.txt
}
public void readIn(){ //*********************************************
try {
FileReader fr = new FileReader(fileName + ".txt");
fileRead = 1;
BufferedReader br = new BufferedReader(fr);
String str;
int line = 0;
while((str = br.readLine()) != null){
score = input.nextInt();
player = input.next();
System.out.println(str);
line++;
score = score + score;
count++;
}
System.out.println(count);
System.out.println(score);
br.close();
}
catch (Exception ex){
System.out.println("There is no shop named: " + fileName);
}
}
}
The way you used BufferReader with Scanner is totally wrong .
Note: you can use BufferReader in Scanner constructor.
For example :
try( Scanner input = new Scanner( new BufferedReader(new FileReader("your file path goes here")))){
}catch(IOException e){
}
Note: your file reading process or other processes must be in try block because in catch block you cannot do anything because your connection is closed. It is called try catch block with resources.
Note:
A BufferedReader will create a buffer. This should result in faster
reading from the file. Why? Because the buffer gets filled with the
contents of the file. So, you put a bigger chunk of the file in RAM
(if you are dealing with small files, the buffer can contain the whole
file). Now if the Scanner wants to read two bytes, it can read two
bytes from the buffer, instead of having to ask for two bytes to the
hard drive.
Generally speaking, it is much faster to read 10 times 4096 bytes
instead of 4096 times 10 bytes.
Source BufferedReader in Scanner's constructor
Suggestion: you can just read each line of your file by using BufferReader and do your parsing by yourself, or you can use Scanner class that gives you ability to do parsing tokens.
difference between Scanner and BufferReader
As a hint you can use this sample for your parsing goal
Code:
String input = "Kick 20";
String[] inputSplited = input.split(" ");
System.out.println("My splited name is " + inputSplited[0]);
System.out.println("Next year I am " + (Integer.parseInt(inputSplited[1])+1));
Output:
My splited name is Kick
Next year I am 21
Hope you can fixed your program by given hints.

FileNotFoundException occurs due to my outputStream method

Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.

Reading a string with new lines from console java

I want to read this string (from console not file) for example:
one two three
four five six
seven eight nine
So I want to read it per line and put every line in an array.
How can I read it? Because if I use scanner, I can only read one line or one word (nextline or next).
what I mean is to read for example : one two trhee \n four five six \n seven eight nine...
You should do by yourself!
There is a similer example:
public class ReadString {
public static void main (String[] args) {
// prompt the user to enter their name
System.out.print("Enter your name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
userName = 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, " + userName);
}
} // end of ReadString class
To answer the question as clarified in the comment on the first answer:
You must call Scanner's nextLine() method once for each line you wish to read. This can be accomplished with a loop. The problem you will inevitably encounter is "How do I know big my result array should be?" The answer is that you cannot know if you do not specify it in the input itself. You can modify your programs input specification to require the number of lines to read like so:
3
One Two Three
Four Five
Six Seven Eight
And then you can read the input with this:
Scanner s = new Scanner(System.in);
int numberOfLinesToRead = new Integer(s.nextLine());
String[] result = new String[numberOfLinesToRead];
String line = "";
for(int i = 0; i < numberOfLinesToRead; i++) { // this loop will be run 3 times, as specified in the first line of input
result[i] = s.nextLine(); // each line of the input will be placed into the array.
}
Alternatively you can use a more advanced data structure called an ArrayList. An ArrayList does not have a set length when you create it; you can simply add information to it as needed, making it perfect for reading input when you don't know how much input there is to read. For example, if we used your original example input of:
one two trhee
four five six
seven eight nine
You can read the input with the following code:
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
result.add(line);
}
So, rather than creating an array of a fixed length, we can simply .add() each line to the ArrayList as we encounter it in the input. I recommend you read more about ArrayLists before attempting to use them.
tl;dr: You call next() or nextLine() for each line you want to read using a loop.
More information on loops: Java Loops
Look at this code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SearchInputText {
public static void main(String[] args) {
SearchInputText sit = new SearchInputText();
try {
System.out.println("test");
sit.searchFromRecord("input.txt");
System.out.println("test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void searchFromRecord(String recordName) throws IOException {
File file = new File(recordName);
Scanner scanner = new Scanner(file);
StringBuilder textFromFile = new StringBuilder();
while (scanner.hasNext()) {
textFromFile.append(scanner.next());
}
scanner.close();
// read input from console, compare the strings and print the result
String word = "";
Scanner scanner2 = new Scanner(System.in);
while (((word = scanner2.nextLine()) != null)
&& !word.equalsIgnoreCase("quit")) {
if (textFromFile.toString().contains(word)) {
System.out.println("The word is on the text file");
} else {
System.out.println("The word " + word
+ " is not on the text file");
}
}
scanner2.close();
}
}

Categories