How to take space separated input in Java using BufferedReader?
Please change the code accordingly, i wanted the values of a, b, n as space seperated integers and then I want to hit Enter after every test cases.
Which means first i'll input the number of test cases then i'll press the Enter key. Then i input the vale of a then i'll press Space, b then again Space then i'll input the value of n, then i'll press the Enter key for the input for the next testcase.
I know that this can be done easily through Scanner but i don't wanna use it because it throws TLE(Time Limit Extended) error on online judges.
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
int testCases = Integer.parseInt(inputString);
double a,b,n,j,t=1;
int i;
int ans [] = new int[testCases];
for(i=0;i<testCases;i++)
{
inputString = br.readLine();
a = Double.parseDouble(inputString);
inputString = br.readLine();
b = Double.parseDouble(inputString);
inputString = br.readLine();
n = Double.parseDouble(inputString);
for(j=0;j<n;j++)
{
if(t==1)
{
a*=2;
t=0;
}
else if(t==0)
{
b*=2;
t=1;
}
}
if(a>b)
ans[i]=(int)(a/b);
else
ans[i]=(int)(b/a);
t=1;
}
for(i=0;i<testCases;i++)
System.out.println(ans[i]);
}catch(Exception e)
{
return;
}
}
First read the number of input lines to be read.
Then parse each line and get the String.
Though I have not added the NumberFormatException handling, but it's a good idea to have that.
Change your for loop like this:
for(i=0;i<testCases;i++){
inputString = br.readLine();
String input[] = inputString.split("\\s+");
a = Double.parseDouble(input[0]);
inputString = br.readLine();
b = Double.parseDouble(input[1]);
inputString = br.readLine();
n = Double.parseDouble(input[2]);
for(j=0;j<n;j++){
if(t==1){
a*=2;
t=0;
}else if(t==0){
b*=2;
t=1;
}
}
if(a>b){
ans[i]=(int)(a/b);
}else{
ans[i]=(int)(b/a);
t=1;
}
}
Related
I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
String s="";
for(int i=0;i<N;i++){
s=sc.nextLine();
}
Eg : N= 10
S = aabbbabbab
How do I take an input of String of n length ?
I am trying to take an input String which must be of length N.
I know the above logic is wrong, but still i am confused ?
PS: The first line of input contains a single integer N − the length of the string.
The second line contains the initial string S itself.
Check if the input String is greater than the maximumlength.
if (s.length() > maximumLength) { // do something
And what you can do is to use a substring in order to trim the input.
fixedInput = s.substring(0, maximumLength - 1);
Okay, as you are reading the number first, you must initialize maximumLength with the first input.
As an alternative you can ask the user until the input fits the entered length:
do {
s = sc.nextLine();
if (s.length() != maximumLength)
System.out.println("The input did not fit the size");
} while (s.length() != maximumLength);
Use this:
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); // N == 5 e.g
sc.nextLine(); // Consume the leftover '\n'
String s = sc.nextLine(); // Hello World
s = s.substring(0, N);
System.out.println(s); // Hello
I would suggest to check the input string using an if and return the user to input again if it doesn't match the length that you are looking for.
Example:
if(s.length() != n) {
//Take another input
}
You can do the above in a loop until this condition is satisfied (maybe a while loop).
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String s="";
do{
s = sc.nextLine();
}while(s.length() != n);
}
In the above code, all you are doing is reading in n strings, and setting s to the last one (there will also be an exception thrown if there aren't n strings in the input stream). What you need to do is read in a string and compensate for any length errors.
if(in.hasNextLine()) {
s = in.nextLine();
if(s.length() > n) s = s.substring(0, n); // Cut the string so it is of the desired length
else {
for(int i = 0; i < n - s.length(); i++) s += " "; // Add spaces until the string is of the desired length
}
}
I'm trying to write a part of a program that reads a text file and then retrieves an integer from each line in the file and adds them together. I've managed to retrieve the integer, however each line contains more than one integer, leading me to inadvertently pick up other integers that I don't need. Is it possible to skip certain integers?
The format of the text file can be seen in the link underneath.
Text file
The integers that i'm trying to collect are the variables that are 3rd from the left in the text file above, (3, 6 and 4) however i'm also picking up 60, 40 and 40 as they're integers too.
Here's the code that i've got so far.
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;
}
Just add input.nextLine():
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}
From the documentation: nextLine advances the scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Another approach would be parsing each line and taking the third column.
BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();
public static double getAverageItems (String filename, int policyCount) throws IOException {
Scanner input = null;
int itemAmount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String []var = input.nextLine().split("\\s+");
itemAmount += var[2];
}
return itemAmount;
}
import java.io.*;
public class inputting {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("number??");
String str;
int i=0;
while (i<5) {
str=br.readLine();
int n = Integer.parseInt(str);
System.out.println(n);
i++;}
}
}
if i want to read 5 integers how do i do that? what extra code i need to write?
You should always use a Java Scanner to read inputs.
To your existing code, assuming String str = br.readLine(); makes str contain the line of at least one integer, eg. "10 20 30 40 50"
What you need to do is:
Scanner sc = new Scanner(str);
While (sc.hasNext())
{
System.out.println(sc.nextInt());
// ...or assign it to an array elment...your choice!
}
If you want to ask multiple times the question number?? you just need to use a for or while loop around these three lines:
System.out.println("number??");
String str = br.readLine();
int n = Integer.parseInt(str);
and add the read numbers to a list so you'd just need to change the last line.
wrap your readline in a while loop that checks for user input to quit
while ( !(str = br.readLine()).equalsIgnoreCase("q")) {
int n = Integer.parseInt(str);
System.out.println(n);
}
This is what I have written so far but when exception is raised it does not again ask the user for input.
do {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = br.readLine();
key = Integer.parseInt(temp);
} while (key < 0 && key > 9);
if (key < 0 || key > 10)
throw new InvalidStartingStonesException(key);
player1 = new KeyBoardPlayer();
player2 = new KeyBoardPlayer();
this.player1 = player1;
this.player2 = player2;
state = new KalaGameState(key);
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
} catch (IOException e) {
System.out.println(e);
}
As soon as that NumberFormatException is thrown, you jump out of the loop and down to the catch. If your try-catch block is inside your while loop, it'll have the effect you're looking for. You may need to adjust the condition on the loop.
An alternative way is to check if the string input matches a regular expression for an integer. If it doesn't match, you ask for the input again.
See Teleteype.readInt() from the Java Project Template. The basics of it is that you read input as a String, and then you convert it to an integer using Integer.parseInt(), which will throw NumberFormatException if the contents of the String is not an integer, which you can handle by catching the NumberFormatException.
What I would recommend is instead of using all these exceptions is to make separate methods that read specific data types. (Ex.)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args){
int n = getInteger("Enter integer: ");
System.out.println(n);
}
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
return Integer.parseInt(in);
}
}
while (true) {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
key = Integer.parseInt(br.readLine());
if (key > -1 && key < 10)
break;
else
System.out.println("Invalid number of stones. Choose from 0 - 9");
}