I need to read an unknown number of inputs using either C++ or Java. Inputs have exactly two numbers per line. I'd need to use cin or a System.in Scanner because input comes from the console, not from a file.
Example input:
1 2
3 4
7 8
100 200
121 10
I want to store the values in a vector. I have no idea how many pairs of numbers I have. How do I design a while loop to read the numbers so I can put them into a vector?
You can use an idiomatic std::copy in C++: (see it work here with virtualized input strings)
std::vector<int> vec;
std::copy (
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(vec)
);
That way, it will append onto the vector each time an integer is read from the input stream until it fails reading, whether from bad input or EOF.
Java:
Scanner sc = new Scanner(System.in);
String inputLine;
while(sc.hasNextLine()) {
inputLine = sc.nextLine();
//parse inputLine however you want, and add to your vector
}
Instead of using a buffered reader, one can use Scanner as follows to accomplish the same
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true)
{
String Line = new String(scan.nextLine());
if(Line.length()==0)
{
break;
}
}
}
}
Only workaround I found :
import java.io.*;
class Solution {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i=1 ;
String line =br.readLine();
while(line.length()>0){
System.out.println(line);
line = br.readLine();
}
}
}
For someone looking for less fancier C++ code:
#include<iostream>
#include<vector>
int main(){
std::vector<int>inputs; //any container
for(int i;std::cin>>i;) //here the magic happens
inputs.push_back(i); //press Ctrl+D to break the loop
for(int num:inputs) //optional
std::cout<<num<<endl;
}
Related
I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}
I just started using Java, so sorry if I ask some very simple questions. I basically have to get the user to continuously integers, and once they enter a negative number, the loop will exit. The code I have written so far does not seem to be able to write the input I get from the user to the file I created, morescores. When I try opening the file or calling it from the main method, it's blank. I've tried searching it up on google, youtube, and on stackoverflow but nothing seems to be working. I"ll appreciate any help I can get :)
package bufferedreader;
import java.io.*;
import java.util.Scanner;
public class BufferedReader {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
writeToFile("morescores");
processFile("morescores");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter (new FileWriter ("morescores.txt"));
int score = 1;
while (true) {
Scanner reader = new Scanner(System.in);
System.out.print ("Enter a number: ");
score = reader.nextInt();
if (score < 0) {
break;
} else {
outputWriter.write(score);
outputWriter.newLine();
}
}
outputWriter.flush();
outputWriter.close();
}
public static void processFile2 (String filename) throws IOException {
java.io.BufferedReader inputReader = new java.io.BufferedReader(new InputStreamReader (new FileInputStream ("morescores.txt")));
String line;
while ((line = inputReader.readLine()) != null) {
System.out.println (line);
}
inputReader.close();
}
}
UPDATE: I fixed the problem haha turns out I was trying to print an integer when it could only be a string. I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value I actually have a followup question, I also need to find the average of all the numbers the user inputs. How would I do that? How can I write a code so that the program knows how many times the user inputs a value
Convert your int to a String before writing to your file so
outputWriter.write(score);
would be:
outputWriter.write(String.valueOf(score));
if you are wondering why it has to be converted first look at the doc:
https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html#write(int)
you'll see that it doesn't write the int but the character represented by the int
If you pass int value to the write method of BufferedWriter class, then it will be consider as character instead of number, therefore with the current code you have written whatever positive number you are providing will get converted to valid char value and then it will be written into the file.
In order to achieve what you are asking for you need to convert your int value to string before writing it to file and to do that you can use any of the below methods :
String.valueOf(score)
Integer.toString(score)
Hi I'm in a programming class over the summer and am required to create a program that reads input from a file. The input file includes DNA sequences ATCGAGG etc and the first line in the file states how many pairs of sequences need to be compared. The rest are pairs of sequences. In class we use the Scanner method to input lines from a file, (I read about bufferedReader but we have not covered it in class so not to familiar with it) but am lost on how to write the code on how to compare two lines from the Scanner method simultaneously.
My attempt:
public static void main (String [] args) throws IOException
{
File inFile = new File ("dna.txt");
Scanner sc = new Scanner (inFile);
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
comparison(DNA1,DNA2);
}
sc.close();
}
Where the comparison method would take a pair of sequences and output if they had common any common characters. Also how would I proceed to input the next pair, any insight would be helpful.. Just stumped and google confused me even further. Thanks!
EDIT:
Here's the sample input
7
atgcatgcatgc
AtgcgAtgc
GGcaAtt
ggcaatt
GcT
gatt
aaaaaGTCAcccctccccc
GTCAaaaaccccgccccc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gctagtacACCT
gctattacGcct
First why you are doing:
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
While you have pairs only in one line not pairs and two lines of input, but number of lines once? Move reading pairs from that while looop and parse it to int, then it does not matter but you could use it to stop reading lines if you know how many lines are there.
Second:
throws IOException
Might be irrelevant but, really you don't know how to do try catch and let's say skip if you do not care about exceptions?
Comparision, if you read strings then string has method "equals" with which you can compare two strings.
Google will not help you with those problems, you just don't know it all, but if you want to know then search for basic stuff like type in google "string comparision java" and do not think that you can find solution typing "Reading two lines from an input file using Scanner" into google, you have to go step by step and cut problem into smaller pieces, that is the way software devs are doing it.
Ok I have progz that somehow wokrked for me, just finds the lines that have something and then prints them out even if I have part, so it is brute force which is ok for such thing:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program
{
public static void main (String [] args) throws IOException
{
File inFile = new File ("c:\\dna.txt");
Scanner sc = new Scanner (inFile);
int pairs = Integer.parseInt(sc.nextLine());
for (int i = 0; i< pairs-1; i++)
{
//ok we have 7 pairs so we do not compare everything that is one under another
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
Boolean compareResult = comparison(DNA1,DNA2);
if (compareResult){
System.out.println("found the match in:" + DNA1 + " and " + DNA2) ;
}
}
sc.close();
}
public static Boolean comparison(String dna1, String dna2){
Boolean contains = false;
for (int i = 0; i< dna1.length(); i++)
{
if (dna2.contains(dna1.subSequence(0, i)))
{
contains = true;
break;
}
if (dna2.contains(dna1.subSequence(dna1.length()-i,dna1.length()-1 )))
{
contains = true;
break;
}
}
return contains;
}
}
I'm trying to use a Delimiter to pull out the first numbers in a document with 31 rows looking something like "105878-798##176000##JDOE" and put it in an int array.
The numbers I'm interesed in are "105878798", and the number of numbers is not consistent.
I wrote this but can't figure out how to change the line when i reach the first delimiter (of the line).
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
int n = 0;
String rad;
File fil = new File("accounts.txt");
int[] accountNr = new int[31];
Scanner sc = new Scanner(fil).useDelimiter("##");
while (sc.hasNextLine()) {
rad = sc.nextLine();
rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(rad);
System.out.println(accountNr[n]);
n++;
System.out.println(rad);
}
}
}
Don't use the scanner for this, use the StringTokenizer and set the delimiter to ##, then just keep calling .nextElement() and you will get the next number no matter how long it is.
StringTokenizer st2 = new StringTokenizer(str, "##");
while (st2.hasMoreElements()) {
log.info(st2.nextElement());
}
(Of course, you can iterate in different ways..)
I would suggest for each line use line.split("[#][#]")[0] (of course haldle your exceptions).
also, rad.replaceAll(...) returns a new String, because String is an imutable object. you should execute parseInt on the returned String and not on rad.
just use the following instead of the equivalent 2 lines in your code:
String newRad = rad.replaceAll("-","");
accountNr[n] = Integer.parseInt(newRad);
I have a bit of an annoying case here; wherein I am not able to take the input properly. I have always taken input via Scanner, and am not used to the BufferedReader.
INPUT FORMAT
First line contains T, which is an integer representing the number of test cases.
T cases follow. Each case consists of two lines.
First line has the string S.
The second line contains two integers M, P separated by a space.
EXAMPLE
Input:
2
AbcDef
1 2
abcabc
1 1
My code so far:
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
int T= Integer.parseInt(inp.readLine());
for(int i=0;i<T;i++) {
String s= inp.readLine();
int[] m= new int[2];
m[0]=inp.read();
m[1]=inp.read();
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
}
}
When inputting to the above example shown, I get the following output:
AbcDef
9
49
2
9
97
BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.
String s= inp.readLine();
int[] m= new int[2];
String[] s1 = inp.readLine().split(" ");
m[0]=Integer.parseInt(s1[0]);
m[1]=Integer.parseInt(s1[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
You can check also Scanner vs. BufferedReader.
You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass.
Although, you can do something like this in regard to your query :
import java.io.*;
class Test
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
for(int i=0;i<t;i++)
{
String str=br.readLine();
String num[]=br.readLine().split(" ");
int num1=Integer.parseInt(num[0]);
int num2=Integer.parseInt(num[1]);
//rest of your code
}
}
}
I hope this will help you.