Input Format
Read some unknown n lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.
Output Format
For each line, print the line number, followed by a single space, and then the line content received as input:
Sample Output
Hello world
I am a file
Read me until end-of-file.
Here is my solution. The problem being I am not able to proceed till EOF.
But the output is just:
Hello world
Here is my code:
public class Solution {
public static void main(String[] args) {
check(1); // call check method
}
static void check(int count) {
Scanner s = new Scanner(System.in);
if(s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
}
Your code does not work because you create a new Scanner object in every recursive call.
You should not use recursion for this anyways, do it iteratively instead.
Iterative version
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int count = 1;
while(s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
}
}
}
Recursive version
public class Solution {
private Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in); // initialize only once
check(1);
}
public static void check(int count) {
if(s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
check(count + 1);
}
}
}
Change
if (s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
to:
while (s.hasNext()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
System.out.print(count);
check(count);
}
while loops continues until the data exists, where as if checks for only once.
Scanner is kind of a BufferedReader (I'm not telling about inheritance or something. I'm telling they both have buffers. Scanner has just a small one). So after you enter text in the Console, those are read() from System.in and stored in the buffer inside the Scanner.
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
s1.hasNext();
Scanner s2 = new Scanner(System.in);
while(true){
System.out.println("Read line:: " + s2.nextLine());
}
}
Use the following input to the Scanner:
line 1
line 2
line 3
line 4
You will get the output:
Read line:: e 1
Read line:: line 2
Read line:: line 3
Read line:: line 4
I think you might know the reason to this output. Some characters of the first line are in the Scanner s1. Therefore don't create 2 Scanners to take input from same Stream.
You can change your code as follows to get required output.
private static Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in);
check(1); // call check method
}
static void check(int count) {
if (s.hasNextLine()) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
You can use s.hasNextLine() instead of s.hasNext() as you are reading line by line.
No need to use s.hasNextLine()==true as that statement will be true if and only if s.hasNextLine() is true.
You can give EOF character to the console using Ctrl+Z in Windows system and Ctrl+D in Unix. As I know, you can't send EOF character using the output window of NetBeans.
If using recursion is a requirement, you can use a helper function:
static void check(int count) {
Scanner s = new Scanner(System.in);
check(count, s);
}
static void check(int count, Scanner scanner) {
if(!scanner.hasNext()) {
return;
}
String ns = scanner.nextLine();
System.out.println(count + " " + ns);
check(++count, scanner);
}
Notice how new Scanner(System.in) is only called once.
public static void main(String[] args) {
List<String> eol = new ArrayList<String>();
Scanner in=new Scanner(System.in);
int t=1;
while(in.hasNext()){
eol.add(in.nextLine());
}
for (String i:eol){
System.out.println(t+" "+i);
t++;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 1;
while(scan.hasNext()){
System.out.println(count++ + " " + scan.nextLine());
}
}
Here is the error free program.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = 1;
while(scan.hasNext()) {
String s = scan.nextLine();
System.out.println(count + " " + s);
count++;
}
}
}
Scanner scanner = new Scanner(System.in);
int i = 1;
while(scanner.hasNext()) {
System.out.println(i + " " + scanner.nextLine());
i++;
}
Use while instead of if,but recursive version is better.Here is iterative version:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
{
int i=0;
while(sc.hasNext()==true)
{
i=i+1;
String s=sc.nextLine();
System.out.println(i+" "+s);
};
}
}
}
java.util.Scanner.hasNext() basically helps you to read the input. This method returns true if this Scanner has another token of any type in its input. Returns false otherwise.
Check below code snippet,
while(sc.hasNext()) {
System.out.println(i + " " + sc.nextLine());
i++;
}
You can find complete code at below link,
https://github.com/hetalrachh/HackerRank/blob/master/Practice/Java/Introduction/EndOfFile.java
you can try like this to get desired result:
public class EOF {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i =1;scan.hasNext();i++) {
String line = scan.nextLine();
System.out.println(i + " " + line);
}
scan.close();
}
}
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i=1; scan.hasNext() ;
System.out.println(i++ +" "+scan.nextLine()));
}
}
Related
So this is my code, and i want to print out a new line saying what the average number of letters used. And i also want to print the longest name written in.. but i cant make it work.. Any suggestions??
import java.util.*;
import java.util.stream.Collectors;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Write some names. When you are finished write <Avslutt>! :)");
ArrayList<String> names = new ArrayList<String>();
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if ("avslutt".equalsIgnoreCase(input)) {
Collections.sort(names);
System.out.println("Here is the result (Alphabetical): " + names);
break;
} else {
names.add(input);
}
}
}
}
You can loop over the input while not empty line, then add to the list and sum the amount to calculate the average.
For sorting the list using Comparater.comparing by string length
public static void main(String[] a) {
Scanner scanner = new Scanner(System.in);
System.out.print("Write some names. When you are finished write <Avslutt>! :)");
List<String> names = new ArrayList<String>();
int amount = 0;
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
if ("".equals(input)) {
break;
} else {
names.add(input);
amount += input.length();
}
}
double avg = amount / names.size();
Collections.sort(names, Comparator.comparing(n -> n.length()));
System.out.println("Longest name: " + names.get(names.size() - 1));
System.out.println("Average letter used: + avg);
scanner.close();
}
I'am trying to call a method called "cnpPacient".After running this i get a NoSuchElementException in the line where i read variable " cnp ".
static void cnpPacient() {
Scanner x = new Scanner(System.in);
System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
int cnp = x.nextInt();
x.close();
}
How can i fix it ?
Works fine for me when provide 2 as input and it printed the same.
public static void main(String[] args) {
cnpPacient();
}
static void cnpPacient() {
Scanner x = new Scanner(System.in);
System.out.println("INTRODUCETI CNP-ul PACIENTULUI :");
int cnp = x.nextInt();
System.out.println(cnp);
x.close();
}
Output:
INTRODUCETI CNP-ul PACIENTULUI :
2
2
Non-CS major here taking my first programming class for fun. As the title states, my first assignment is "Write a program that prints out every line of input exactly as they were entered." My program right now will accept one input, but not any others. How can I fix this? Thank you so much :)
import java.util.Scanner;
public class echohw {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans;
ans = in.nextLine();
System.out.print(ans);
Like Scary Wombat said, use a while loop:
import java.util.Scanner;
public class echohw {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans;
// Continue printing user input unless "stop" is entered
while (!(ans = in.nextLine()).equals("stop"))
System.out.println(ans);
}
}
You can use array function to store multiple user inputs. In this example, I try to make it simple so you can understand it well. If you have any other doubt, you can ask me here.
import java.util.Scanner;
public class echohw {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide number of inputs
System.out.println("How many inputs you want to enter: ");
int numInput = Integer.parseInt(scan.nextLine());
//Store inputs
String aryInput[] = new String[numInput];
for (int i = 0; i < aryInput.length; i++) {
System.out.println("Enter the input " + (i+1) + " : ");
aryInput[i] = scan.nextLine();
}
//Print inputs
for (int i = 0; i < aryInput.length; i++) {
System.out.println("Input " + (i+1) + " : ");
System.out.println(aryInput[i] + "\n");
}
}
}
My current code is as follows, I need to print the user's input using the outputWithoutWhitespace() method but I am having a hard time understanding where to apply it/how to actually use it. I believe I should be using \t. How can I take away the whitespace when printing with the outputWithoutWhitespace() method?
import java.util.Scanner;
public class TextAnalyzer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = " ";
int getNumOfCharacters = 0;
int count = 0;
System.out.println("Enter a sentence or phrase: ");
userInput = scnr.nextLine();
System.out.println("You entered: " + userInput);
count = getNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int getNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
}
package whitesp;
import java.util.Scanner;
public class TextAnalyzer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = " ";
int getNumOfCharacters = 0;
int count = 0;
System.out.println("Enter a sentence or phrase: ");
userInput = scnr.nextLine();
System.out.println("You entered: " + userInput);
count = getNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int getNumOfCharacters(String userInput) {
String omitSpace=userInput.replace(" ","");
int userCount = omitSpace.length();
return userCount;
}
}
import java.io.IOException;
import java.util.Scanner;
public class web_practice {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int l = input.indexOf(' ');
String cmd = input.substring(0, l);
String end = input.substring(l);
if (cmd.equals("define"));
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" + end));
}
}
I was trying to make a code to find the definition of a word by connecting it to dictionary.com and checking if they say the word "define" as the first word?
The splitting is not working.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int words[] = input.split(' ');
if (words[0].equalsIgnoreCase("define")) {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" + words[0]));
}
}
import java.io.*;
public class Sol {
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[2];
input = in.readLine().split(" ");
int a;
int b;
a = Integer.parseInt(input[0]);
b = Integer.parseInt(input[1]);
System.out.println("You input: " + a + " and " + b);
}
}
this code will work for you
String[] strArr = input.split(" ") ;
if(strArr[0].equals("define"){
}
Your problem is that you are using Scanner which default behavior is to split the InputStream by whitespace. Thus when you call next(), your input string contains the command only, not the whole line. Use Scanner.nextLine() method instead.
Also take a note that String end = input.substring(l); will add a space into the end string. You probably want to use String end = input.substring(l+1);. Here's the fixed main method:
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int l = input.indexOf(' ');
if(l >= 0) {
String cmd = input.substring(0, l);
String end = input.substring(l+1);
if (cmd.equals("define"));
java.awt.Desktop.getDesktop().browse(
java.net.URI.create("http://dictionary.reference.com/browse/" + end));
}
}
Scanner scanner = new Scanner(System.in);
String input = scanner.next();;
String[] inputs = input.split(" ");
if (inputs[0].equalsIgnoreCase("define")){ java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://dictionary.reference.com/browse/" ));}
The problem I see in your code is using scanner.next(); the next() method will read the next token without space for ex for console input define blabla the value of input variable would be define ie without space so in your case there is no space character so input.indexOf(' '); will return -1 giving exception for substring() a quickfix would be change the line scanner.next(); to scanner.nextLine(); which would read the whole line rather than token.