How to take input in Java this way? - java

I want to take the inputs for the length, breadth and height of my "Box" class repectively. Now I want to take it as a stream of integers and then set them individually to each of the dimension of the box. The stream will be taken as i/p until the user presses 0. So I wrote it this way (I am just mentioning the main method, I defined the box class seperately):
public static void main(String args[])
{
System.out .print("Enter length, breadth and height->> (Press '0' to end the i/p)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while((br.read())==0)
{
// What should I write here to take the input in the required manner?
}
}
PS: I cannot use scanner, console or DataInputStream. So help me here with BufferedReader.

Since you indicated you absolutely must use the BufferedReader, I believe one way to do this is to use the BufferedReader#readLine() method instead. That will give you the full line as entered by the user, up to the line termination (either a '\r' or '\n' according to the documentation).
As Zong Zheng Li already said, while the Scanner class can tokenize the input line for you, since you cannot use that, you'll have to do that yourself manually.
At this moment, one way that springs to mind is to simply split on a space (\s) character. So your code might look something like this:
System.out .print("Enter length, breadth and height->> (Press '0' to end the i/p)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String inputLine = br.readLine(); // get user input
String[] inputParts = inputLine.split("\\s+"); // split by spaces
int width = Integer.parseInt(inputParts[0]);
int height = Integer.parseInt(inputParts[1]);
int breadth = Integer.parseInt(inputParts[2]);
Note that I'm not showing any error or range checking, or input validation, as I'm just showing a general example.
I'm sure there's plenty of other ways to do this, but this is the first idea that popped in my mind. Hope it helps somewhat.

Is there a particular reason you're not just using Scanner? It tokenizes and parses values for you:
Scanner sc = new Scanner(System.in);
int width = sc.nextInt();
int height = sc.nextInt();

Maybe you can try this one.
public static void main(String args[])
{
String input = 0;
ArrayList<int> list = new ArrayList<int>();
boolean exit = true;
System.out.print("Enter length, breadth and height->> (Press '0' to end the i/p)");
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while((input = br.readLine()!=null && exit)
{
StringTokenizer t = new StringTokenizer(input);
while(t.hasMoreToken()){
if(Integer.parseInt(t.nextToken()) != 0){
list.add(input);
}
else{
exit = false;
}
}
}
//list contains your needs.
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}

Related

Using Scanner and Arrays's to add BigInts

This is a project from school, but i'm only asking for help in the logic on one small part of it. I got most of it figured out.
I'm being given a file with lines of string integers, for example:
1234 123
12 153 23
1234
I am to read each line, compute the sum, and then go to the next one to produce this:
1357
188
1234
I'm stuck on the scanner part.
public static void doTheThing(Scanner input) {
int[] result = new int[MAX_DIGITS];
while(input.hasNextLine()) {
String line = input.nextLine();
Scanner linesc = new Scanner(line);
while(linesc.hasNext()) {
String currentLine = linesc.next();
int[] currentArray = convertArray(stringToArray(currentLine));
result = addInt(result, currentArray);
}
result = new int[MAX_DIGITS];
}
}
In a nutshell, I want to grab each big integer, put it an array of numbers, add them, and then i'll do the rest later.
What this is doing it's basically reading all the lines and adding everything and putting it into a single array.
What i'm stuck on is how do I read each line, add, reset the value to 0, and then read the next line? I've been at this for hours and i'm mind stumped.
Edit 01: I realize now that I should be using another scanner to read each line, but now i'm getting an error that looks like an infinite loop?
Edit 02: Ok, so after more hints and advice, I'm past that error, but now it's doing exactly what the original problem is.
Final Edit: Heh....fixed it. I was forgetting to reset the value to "0" before printing each value. So it makes sense that it was adding all of the values.
Yay....coding is fun....
hasNext method of the Scanner class can be used to check if there is any data available in stream or not. Accordingly, next method used to retrieve next continuous sequence of characters without white space characters. Here use of the hasNext method as condition of if doesn't make any sense as what you want is to check if the there are any numerical data left in the current line. You can use next(String pattern).
In addition, you can try this solution even though it is not optimal solution...
// In a loop
String line = input.nextLine(); //return entire line & descard newline character.
String naw[] = line.split(" "); //split line into sub strings.
/*naw contains numbers of the current line in form of string array.
Now you can perfom your logic after converting string to int.*/
I would also like to mention that it can easily & efficiently be done using java-8 streams.
An easier approach would be to abandon the Scanner altogether, let java.nio.io.Files to the reading for you and then just handle each line:
Files.lines(Paths.get("/path/to/my/file.txt"))
.map(s -> Arrays.stream(s.split("\\s+")).mapToInt(Integer::parseInt).sum())
.forEach(System.out::println);
If i were you i would be using the BufferedReader insted of the Scanner like this:
BufferedReader br = new BufferedReader(new FileReader("path"));
String line = "";
while((line = br.readLine()) != null)
{
int sum = 0;
String[] arr = line.split(" ");
for(String num : arr)
{
sum += Integer.parseInt(num);
}
System.out.println(sum);
}
Considering the level you're on, I think you should consider this solution. By using only the scanner, you can split the lines into an array of tokens, then iterate and sum the tokens by parsing them and validating that they're not empty.
import java.util.*;
class SumLines {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
while(S.hasNext()) {
String[] tokens = S.nextLine().split(" ");
int sum = 0;
for(int i = 0; i < tokens.length; i++) {
if(!tokens[i].equals("")) sum += Integer.parseInt(tokens[i]);
}
System.out.println(sum);
}
}
}

Java: Read input without knowing number of input lines

This might be very very basic or may be something I am totally missing. I have started doing some competitive programming on online channels. I have to read comma separated strings and do some manipulations around it but the problem is that I do not know the number of lines of input. Below is the input example
Input 1
John,Jacob
Lesley,Lewis
Remo,Tina
Brute,Force
Input 2
Hello,World
Java,Coder
........
........
//more input lines
Alex,Raley
Michael,Ryan
I am trying to read input and breaking when end of the line is encountered but with no luck. This is what I have been trying
//1st method
Scanner in = new Scanner(System.in);
do{
String relation = in.nextLine();
//do some manipulation
System.out.println(relation);
}while(in.nextLine().equals("")); //reads only first line and breaks
//2nd method
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String relation = in.next();
System.out.println(relation);
if(relation.equals("")){
break;
}
}
//3rd method
Scanner in = new Scanner(System.in);
while(true){ //infinite loop
String relation = in.nextLine();
System.out.println(relation);
if(relation.equals("")){
break;
}
}
Can somebody help here.
PS: Please don't judge. I am new to competitive programming though I know how to take user input in java and difference between next() and nextLine().
Im not gonna write why you shouldn't use Scanner. There are numerous articles why you shouldn't use Scanner in competitive programming. Instead use BufferedReader.
In competitive programming they redirect the input to your code from file.
It works like ./a.out > output.txt < input.txt for example.
So read until null is detected in the while loop.
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s = br.readLine()) != null)
{
//System.out.println(s);
}
}
For testing through your keyboard, to simulate a null from your keyboard:
Press Ctrl+D. It will break out of the while loop above.
It should be fairly easy. Try
while(in.hasNextLine()){
String relation = in.nextLine();
if("exit".equalsIgnoreCase(relation))break;
//do some manipulation
System.out.println(relation);
}
The method Scanner#hasNextLine simply checks if there is a next line in the input, doesn't really advance the scanner. On the other hand, Scanner#nextLine reads the input as well as advances the scanner.
Update you might want to put some condition to exit the loop. E.g. the above snippet stops reading more input after it encounters a string "exit".
All your methods can be improved.
But let's consider your second method of while loop.
Scanner in = new Scanner(System.in);
String s;
while(in.hasNext()){
s=in.nextLine();
System.out.println(s);
}
In the same way, you can change each of your codes.
Also you can use BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); to buffer your input then check for in.readLine()) != null
Other than the above two methods (Buffered Reader method & Scanner method), I have another method for solving this issue. Have a look at the following code, you can catch NoSuchElementException to solve this issue , though I didn't recommended this as Exception handling is a costly process .
Out of all the methods, the Buffered should only be used during Competitive Coding as it has the least Complexity.
import java.util.*;
public class Program
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
try
{
while(true)
String a=sc.next();
System.out.print(a);
}
catch(NoSuchElementException k)
{
}
}
}

How to pull int value from text file of strings and ints?

I'm trying to write a program that is practically a stack. Given a text file with certain keywords, I want my program to evaluate the text line by line and perform the requested action to the stack.
For example, if the input file is:
push 10
push 20
push 30
The resulting stack should look like:
30
20
10
However, I don't know how to push these values into the stack without hardcoding an int value after the word push. I made a String variable and assigned it to scanner.nextLine()
From there, I compare the line with strLine: if strLine is equal to push followed by some Number, then that number would be pushed on the stack.
However, it seems that the method nextInt() isn't taking this number from the input stream.
Scanner input = new Scanner(file)
int number;
String strLine;
while (input.hasNextLine()){
strLine = input.nextLine();
number = input.nextInt();
if(strLine.equals("push " + number)){
stack.push(number);
}
How can I fix this?
Thank you.
Get the input and split it with space " "!
That will give ["push","1"]
convert the first index to int and then push the value to stack!
while (input.hasNextLine()){
String[] strLine = input.nextLine().split(" ");
if(strLine[0].equals("push")){
stack.push(Integer.parseInt(strLine[1]));
}
else if(strLine[0].equals("pop")){
stack.pop();
}
else{
system.out.println("Please enter a valid input!");
}
}
Hope it helps!
input.nextLine reads the whole line, including the number. What you can do instead is to use input.next() to get the "push" and input.nextInt() to get the number. This example is using Scanner with System.in (so it needs "quit" to exit the while loop), but it should also work with a file (in which case you don't need to type "quit" to exit the program, as it will do so automatically when the input file has no more input). The advantage of using parseInt (as some of the other answers have suggested) is that you can catch any errors in integer input using a try/catch block.
import java.util.Scanner;
import java.util.Stack;
import java.util.InputMismatchException;
public class StackScanner {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner input = new Scanner(System.in);
int number;
String strLine;
while (input.hasNext()){
strLine = input.next();
if(strLine.equals("push")){
try {
number = input.nextInt();
stack.push(number);
} catch ( InputMismatchException e) {
System.out.println("Invalid input. Try again.");
input.nextLine();
continue;
}
} else {
break;
}
}
System.out.println(stack);
}
}
Sample output:
push 5
push 6
push 3
quit
[5, 6, 3]
change this:
number = input.nextInt();
to this:
number = Integer.parseInt(input.nextLine());
nextLine method parses the whole line including any numbers in the line. So, you need to take care of splitting the line and parsing the number in your code.
Something like below will work where I split the line with spaces. Although, there are many such ways possible.
Scanner input = new Scanner(file);
String strLine;
Stack<Integer> stack = new Stack<>();
int number;
while (input.hasNextLine()){
strLine = input.nextLine();
if(strLine.startsWith("push")){
String[] sArr = strLine.split("\\s+");
System.out.println(strLine);
if(sArr.length==2){
number=Integer.parseInt(sArr[1]);
stack.push(number);
System.out.println(number);
}
}
}
If I understand your problem, I would simply tokenize the line by splitting on whitespace.
It looks like your input is relatively structured: you have a keyword of some kind then whitespace then a number. If your data is indeed of this structure, split the line into two tokens. Read the value from the second one. For example:
String tokens[] = strLine.split(" ");
// tokens[0] is the keyword, tokens[1] is the value
if(tokens[0].equals("push")){
// TODO: check here that tokens[1] is an int
stack.push(Integer.parseInt(tokens[1]));
} else if (tokens[0].equals("pop")) { // maybe you also have pop
int p = stack.pop();
} else if ... // maybe you have other operations

A java program to find out the frequrncy of a word using Scanner class

Can any one tell me that how to use Scanner Class of Java to find the frequency of a word in a sentence.
I am confused as to enter a line in java i have to use nextInt() function but to compare need it to convert in char so how to do so.
For example:-
I enter on terminal window(Giving Input)
This is my cat.
Now i have to find the FREGUENCY of word "this" in the above sentence. Please can you give me some idea.REMEMBER THE RESTRICTION IMPOSED ON IT IS I HAVE TO USE ONLY SCANNER CLASS OF JAVA LIBRARY
PROGRAMME USING STREAM READER IS AS FOLLOWS-
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String: ");
String s=br.readLine();
System.out.println("Enter substring: ");
String sub=br.readLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
alternative solution using pattern
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
Pattern p = Pattern.compile(word);
Matcher m = p.matcher(sentence);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
try out this.
public class JavaApplication20 {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();
System.out.print("Enter a word:\t");
String word = scanner.nextLine();
int count = 0;
while (!sentence.equals("")){
if(sentence.contains(word)){ // check if the word is in the sentence; if yes cut the sentence at the index of the first appearance of the word plus word length
// then check the rest of the sentence for more appearances
sentence = sentence.substring(sentence.indexOf(word)+word.length());
count++;
}
else{
sentence = "";
}
}
System.out.println("in your sentence the frequency of \""+word+"\" is:\t" + count);
}
}
You can enter a String too using Scanner Class . Here is your code that i modified , and it working . `
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the String: ");
String s=in.nextLine();
System.out.println("Enter substring: ");
String sub=in.nextLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
//i+sub.length() is used to reduce comparisions
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
The nextLine() method of Scanner class let you input Strings.
Don't listen to #Uzochi. His answers may work, but they're way too complicated and may actually slow your program down.
For the Scanner class, there are multiple ways of reading in numbers or text:
nextInt() - scans in the next integer value
nextDouble() - scans in the next double value
nextLine() - scans in the next line of text
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html - scroll down to method summary, and in the middle of all of the methods, you will find all of the "next" methods.
Note that there is a small bug with Scanner (at least with the last time I used it). Say you're using a Scanner called scan. If you call
scan.nextInt();
scan.nextLine();
(which reads in an integer and then a line of text), your Scanner will skip the call to nextLine(). This is a small bug that can easily be fixed by adding another nextLine(). It will catch the second nextLine.
In response to #Uzochi, there is a much simpler solution to your algorithm. Your algorithm is actually faster than his, although there are some small things that could make your program run a tiny bit faster:
1) Use a while loop instead of a for loop. Your use of indexOf() makes the current index of the String s you're at skip forward a lot, so there's virtually no point in having a for loop. You can easily change it into a while loop. Your conditions would be to keep checking if indexOf() returns a non-negative value (-1 means there is no value), and you increment that index value by 1 (like the for loop does automatically).
2) Smaller thing - you don't need the line:
ind=-1;
Your current code will always modify ind before it hits that if statement, so there is virtually no reason to have this line in the program.
EDIT - #Uzochi may be using Java's built in libraries, but for a beginner like OP, you should be learning how to use for and while loops to efficiently write code.

How to take integer and remove other data types from the file java?

I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks

Categories

Resources