I'm working on a question where I need to store and use the data given by the user. The data given by the user is usually in the below format.
Input:
5
0
4 5 1 0
1 0
5 3 0
3 0
Let's say the user enters a value for 'N' where N>1 and N<500.
In the above example, N=5;
so now, there will be N lines available for the user to enter numbers between 1 and 100 again.
According to the above example, the next N (here N=5) lines contains numbers given randomly by the user. Each line can contain one number or more than 1 which are separated by the spaces. But the code should break after 5 lines are finished. The user should not be able to enter any more data after N lines.
My question is, how can i take the input from the user where there should be N lines and each line can store one or more than one value (<=100)(each value separated by spaces) and should end after the N lines are finished.
I'm not able to come up with any solution. kindly help me on giving me some ideas on how can i go about with it. Thanks.
You can use this for example
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
while (!line.equals("")) {
// what ever you has to do
System.out.println(line);
line = reader.nextLine();
}
}
This code read lines until the user press enter and dont have an input
Related
I am curious how to get input data formatted from a user in java, for example if the user enters 1,2,3 how can I get these numbers in an array when the input look like this:
Scanner s = new Scanner();
String inputString = s.nextLine();
I can get a single number
Integer num = Integer.parseInt(inputString)
but I am unsure how handling multiple numbers would go
Well, you'd use... scanner. That's what it is for. However, out of the box a scanner assumes all inputs are separated by spaces. In your case, input is separated by a comma followed by/preceded by zero or more spaces.
You need to tell scanner this:
Scanner s = new Scanner(System.in);
s.useDelimiter("\\s*,\\s*");
s.nextInt(); // 1
s.nextInt(); // 2
s.nextInt(); // 3
The "\\s*,\\s*" think is a regexp; a bit of a weird concept. That's regexpese for 'any amount of spaces (even none), then a comma, then any amount of spaces'.
You could just use ", " too, that'll work, as long as your input looks precisely like that.
More generally if you have a fairly simple string you can use someString.split("\\s*,\\s*") - regexes are used here too. This returns a string array with everything between the commas:
String[] elems = "1, 2, 3".split("\\s*,\\s*");
for (String elem : elems) {
System.out.println(Integer.parseInt(elem));
}
> 1
> 2
> 3
enter link description here
This is the link to the question. I have written this code in java but I am not getting the correct output.Why?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0; i<n; i++)
{
String name = sc.nextLine();
String even="";
String odd ="";
for(int j=0; j<name.length(); j++)
{
if(j%2==0)
even=even+String.valueOf(name.charAt(j));
else
odd=odd+String.valueOf(name.charAt(j));
}
System.out.println(even+" "+odd);
This is the error I am getting.
Input (stdin)
2
Hacker
Rank
Your Output (stdout)
// a blank space here.
Hce akr
Expected Output
Hce akr
Rn ak
Your int n = sc.nextInt(); consumes the integer that's input (2), but there is a still a newline.
When your loop goes through the first time, and you call String name = sc.nextLine();, it will consume that remaining newline (and nothing else). Hence, your blank line.
To get past that, make sure to read in the new line after you read in n
Also, the last entry isn't shown because you likely need a trailing newline (one after "Rank" in your input)
your code is correct but the problem is in your input taking.
if u take this as a input
2
Hacker
Rank
then your excepted output never come as u mentioned in your question.
Now i tell u in brief about where is the problem:---------
int n = sc.nextInt();
here u take integer input 2 but you delare only one string type variable.u must declare 2string typr variable if u choose 2.
otherwise only 1 tring willl be handled .
Hacker
Rank
thatswhy u take 2 string variable bt according to ur code only hacker will be compiled and give the output.
u declare 2 string variable .
Question explaination: as some of the comments suggested, I will try my best to make this question clearer. The inputs are from a file and the code is just one example. Supposedly the code should work for any inputs in the format. I understand that I need to use Scanner to read the file. The question would be what code do I use to get to the output.
Input Specification:
The first line of input contains the number N, which is the number of lines that follow. The next
N lines will contain at least one and at most 80 characters, none of which are spaces.
Output Specification:
Output will be N lines. Line i of the output will be the encoding of the line i + 1 of the input.
The encoding of a line will be a sequence of pairs, separated by a space, where each pair is an
integer (representing the number of times the character appears consecutively) followed by a space,
followed by the character.
Sample Input
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output for Sample Input
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
I have only posted two questions so far, and I don't quite understand the standard of a "good" question and a "bad" question? Can someone explain why this is a bad question? Appreciate it!
Complete working code here try it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CharTask {
public static void main(String[] args) {
List<String> lines = null;
try {
File file = new File("inp.txt");
FileInputStream ins =new FileInputStream(file);
Scanner scanner = new Scanner(ins);
lines = new ArrayList<String>();
while(scanner.hasNext()) {
lines.add(scanner.nextLine());
}
List<String> output = processInput(lines);
for (int i=1;i<output.size(); i++) {
System.out.println(output.get(i));
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static List<String> processInput(List<String> lines){
List<String> output = new ArrayList<String>();
for (String line: lines) {
output.add(getProcessLine(line));
}
return output;
}
private static String getProcessLine(String line) {
if(line.length() == 0) {
return null;
}
String output = "";
char prev = line.charAt(0);
int count = 1;
for(int i=1;i<line.length();i++) {
char c = line.charAt(i);
if (c == prev) {
count = count +1;
}
else {
output = output + " "+count + " "+prev;
prev = c;
count = 1;
}
}
output = output + " "+count+" "+prev;
return output;
}
}
Input
(inp.txt)
4
+++===!!!!
777777......TTTTTTTTTTTT
(AABBC)
3.1415555
Output
3 + 3 = 4 !
6 7 6 . 12 T
1 ( 2 A 2 B 1 C 1 )
1 3 1 . 1 1 1 4 1 1 4 5
There are two different problems you need to address, and I think it is going to help you to address them separately. The first is to read in the input. It's not clear to me whether you are going to prompt for it and whether it is coming from the console or a file or what exactly. For that you will want to initialize a scanner, use nextInt to get the number of lines, call nextLine() to clear the rest of that line and then run a for loop from 0 up to the number of lines, reading the next line (using nextLine()) into a String variable. To make sure that is working well, I would suggest printing out the unaltered string and see if what is coming out is what is going in.
The other task is to convert a given input String into the desired output String. You can work on that independently, then pull things back together later. You will want a method that takes in a string and returns a string. You can test it by passing the sample Strings and seeing if it gives you back the desired output strings. Set the result="". Looping over the characters in the String using charAt, it will want variables for the currentCharacter and currentCount, and when the character changes or the end of the string is encountered, concatenate the number and character onto the string and reset the character count and current character as needed. Outside the loop, return the result.
Once the two tasks are solved, pull them together by printing out what the method returns for the input string as opposed to the input string itself.
I think that gives you direction on the method to use. It's not a full-blown solution, but that's not what you requested or needed.
Disclaimer:
The parsing-problem described in here is very simple. This question does not simply ask for a way to achieve the parsing. - That's almost straightforward - Instead, it asks for an elegant way. That elegant way would probably be one which does not first read line-wise and then parse each line on its own, as this is obviously not necessary. However, is this elegant way possible with ready to use standard classes?
Question:
I have to parse text of the following form in java (there is more than these 3 records; records can have way more lines than these examples):
5
Dominik 3
Markus 3 2
Reiner 1 2
Samantha 4
Thomas 3
4
Babette 1 4
Diana 3 4
Magan 2
Thomas 2 4
The first number n is the number of lines in the record directly following. Each record consists of a name and then 0 to n integers.
I thought that using java.util.Scanner is a natural choice, but it leads to the nastiness that when using hasNextInt() and hasNext() to determine if a line is started, I can't distinguish if a read number is the header of the next record or it's the last number behind the last name of the previous record. Example from above:
...
Thomas 3
4
...
Here, I don't know how to tell if the 3 and the 4 is a header or belongs to the current line of Thomas.
Sure I can first read line by line, put them into another Scanner, and then read them again, but this effectively parses the whole data twice, which looks ugly to me. Is there a better way?
I would need something like a flag which tells me if a line break was encountered during the last delimiter skipping operation.
Read the file using FileReader and BufferedReader and then start checking :
outer loop -->while readLine is not null
if line matches //d+ --> read value of number and put it into count
from 0 to count do what you want to do // inner loop
Instead of reading into a separate scanner, you can read to end of line, and use String.split, like this:
while (scanner.hasNextInt()) {
int count = scanner.nextInt();
for (int i = 0 ; i != count ; i++) {
if (!scanner.hasNext()) throw new IllegalStateException("expected a name");
String name = scanner.next();
List<Integer> numbers = new ArrayList<Integer>();
for (String numStr : scanner.readLine().split(" ")) {
numbers.add(Integer.parseInt(numStr));
}
... // Do something with name and numbers
}
}
This approach avoids the need to detect the difference between the last int on a line vs. the first integer on next line by calling readLine() after reading a name, i.e. in the middle of reading a line.
File file = new File("records.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
/* Read file one line at a time */
while((line = reader.readLine()) != null){
int noOfRecords = Integer.parseInt(line);
/* read the next n lines in a loop */
while(noOfRecords != 0){
line = reader.readLine();
String[] tokens = line.split(" ");
noOfRecords--;
// do what you need to do with names and numbers
}
}
Here we're reading one line at a time, so the first time we read a line it will be an int (call it as n), from there read the next n lines in some inner loop. Once it's done with this inner loop it will come outside and the next time you read a line it's definitely another int or EOF. That way you don't have to deal with integer parsing exceptions and we'll read all the lines only once :)
I need to do an assignment where I have to write a while loop with a condition like:
while (not end of stream) {
}
I'm confused about the "not end of stream part". How do I make it so it stop reading when there is no integer input in the console? It will be entered like this: 1 2 3 4 5 6 7 8 9.
I am using the Scanner class my code is something like this:
Scanner myScanner = new Scanner(System.in);
int inputValue = userInput.nextInt();
while(not end of stream) {
if (.......) {
....
} else {
....
}
}
Thanks!
Don't let the word stream confuse you, when reading from System.in, there is no continuous 'flow' of numbers coming.. The user can type what ever he wants to and as long as he wants to. Until he hits 'Enter' nothing will happen.
That said, the scenario is more like this:
1 user types 71 2 30 5 1 and hits Enter
2 userInput.nextInt(); will return the first int it finds so here 71
3 now you could do something like this: [EDITED]
public static void main(String[] args) {
System.out.print(">");
Scanner userInput = new Scanner(System.in);
int inputValue = userInput.nextInt();
while (userInput.hasNextInt()) {
System.out.println("you just wrote: " + userInput.nextInt());
}
userInput.close();
}
So until the scanner doesn't find any input that is not an int the loop will continue. In other words, when the user types for example an 'b' the loop terminates.
Now it all depends on what you have to do in your while-loop. You could test for userInput.hasNext() to see if anything comes, or userInput.nextLine() which will wait for an Enter .. or what ever you need.
When I run the above main and type in:[ 1 Enter 2 Enter 3 Enter 4 Enter a Enter ], this is the output:
>1 // <-- this is the number before the while loop
2 // <-- now another number
you just wrote: 2 // <-- and the while loop makes its first iteration
3 // <-- then it waits for you to input the 3rd number
you just wrote: 3 // <-- to make its next iteration
4 // <-- and the 4th
you just wrote: 4 // <-- 4th iteration
a // <-- until you type something else
// end of program
The user always has to hit Enter – otherwise the operation system won't give the typed input to the Java program. This has to do with the settings of the Shell / Console that your operation system provides for the Java program to run. So, Java won't see anything of the input until you hit enter.