I was trying to solve the problem on spoj but my answer is not accepting giving wrong answer i want to know difference between these two chunks of code.
Spoj accepting this
public class Test {
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader r = new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
String s;
while (!(s = r.readLine()).startsWith("42"))
System.out.println(s);
}
}
but Spoj not accepting this
class Test {
public static void main(String[] args) throws java.io.IOException {
new Test().universe();
}
public void universe() throws java.io.IOException {
System.out.println("Enter Number");
java.util.Scanner scan = new java.util.Scanner(System.in);
String input;
while (!(input = scan.next()).startsWith("42")){
System.out.println(input);
}
scan.close();
}
}
here's the problem http://www.spoj.com/problems/TEST/
The first snippet reads the file line by line whereas the other one reads token by token. If there are more than one token per line, the result may be different.
Finally, both codes take the risk of reading the file without checking there is still something to read. In the first case it could throw a NullPointerException and in the second case a NoSuchElementException.
The difference is that scan.next() is a blocking call - if there's no input, the call will wait until there is input.
You need to change your loop for the scanner to this:
while (scan.hasNext()) {
String input = scan.next();
if (input.startsWith("42")) {
System.out.println(input);
}
}
Next is reading next token, maybe you meant nextLine.
Also, you are printing "Enter number" in the latter.
Related
It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
I got an run time exception in my program while I am reading a file through a Scanner.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Day1.ReadFile.read(ReadFile.java:49)
at Day1.ParseTree.main(ParseTree.java:17)
My code is:
while((str=sc.nextLine())!=null){
i=0;
if(str.equals("Locations"))
{
size=4;
t=3;
str=sc.nextLine();
str=sc.nextLine();
}
if(str.equals("Professions"))
{
size=3;
t=2;
str=sc.nextLine();
str=sc.nextLine();
}
if(str.equals("Individuals"))
{
size=4;
t=4;
str=sc.nextLine();
str=sc.nextLine();
}
int j=0;
String loc[]=new String[size];
while(j<size){
beg=0;
end=str.indexOf(',');
if(end!=-1){
tmp=str.substring(beg, end);
beg=end+2;
}
if(end==-1)
{
tmp=str.substring(beg);
}
if(beg<str.length())
str=str.substring(beg);
loc[i]=tmp;
i++;
if(i==size ){
if(t==3)
{
location.add(loc);
}
if(t==2)
{
profession.add(loc);
}
if(t==4)
{
individual.add(loc);
}
i=0;
}
j++;
System.out.print("\n");
}
with Scanner you need to check if there is a next line with hasNextLine()
so the loop becomes
while(sc.hasNextLine()){
str=sc.nextLine();
//...
}
it's readers that return null on EOF
ofcourse in this piece of code this is dependent on whether the input is properly formatted
I also encounter with that problem.
In my case the problem was that i closed the scanner inside one of the funcs..
public class Main
{
public static void main(String[] args)
{
Scanner menu = new Scanner(System.in);
boolean exit = new Boolean(false);
while(!exit){
String choose = menu.nextLine();
Part1 t=new Part1()
t.start();
System.out.println("Noooooo Come back!!!"+choose);
}
menu.close();
}
}
public class Part1 extends Thread
{
public void run()
{
Scanner s = new Scanner(System.in);
String st = s.nextLine();
System.out.print("bllaaaaaaa\n"+st);
s.close();
}
}
The code above made the same exaption, the solution was to close the scanner only once at the main.
You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine() method before each call to nextLine(), make sure the correct encoding is passed to the Scanner constructor, e.g.:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.
For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.
Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called
"java.util.NoSuchElementException: No line found".
If you have to call "sc.nextLine()" n times, then you have to have at least n lines.
Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.
Need to use top comment but also pay attention to nextLine(). To eliminate this error only call
sc.nextLine()
Once from inside your while loop
while (sc.hasNextLine()) {sc.nextLine()...}
You are using while to look ahead only 1 line. Then using sc.nextLine() to read 2 lines ahead of the single line you asked the while loop to look ahead.
Also change the multiple IF statements to IF, ELSE to avoid reading more than one line also.
I ran into this problem, my structure was:
1 - System
2 - Registration <-> 3 - validate
I was closing Scanner on each of the 3 steps. I started to close the Scanner only in system and it solved.
I want to write a method that has a Scanner parameter associated with a stream of input and counts the number of Strings within the input. However, I have a stack overflow exception. Can you tell me the reason? Thank you a lot.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(count(input));
}
public static int count(Scanner input) {
if (input.hasNextLine())
return 1 + count(input);
else
return 1;
}
}
You need to call nextLine() on input in the line return 1 + count(input). You are checking for the next line, but nothing actually consumes it. This means the Scanner never runs out of lines to process.
Since your question states that you want to count the number of strings in a given input, then the code below will do just that, recursively. The other answer's suggestion counts the number of lines in a given input.
Note: Scanner#next() uses spaces (' ') as the default delimiter.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(count(input));
}
public static int count(Scanner input) {
if (input.hasNext()) {
input.next(); // move Scanner's position to the next string
return 1 + count(input);
}
return 0;
}
}
Input:
The dog barks loudly.
Output:
4
I have tried to solve the 3n+1 problem, and got very close. I think what happens here is the answer should accept multiple lines of input at once should not ask the user to give input again. I have tried the nextLine() method in a loop conditioned by the hasNextLong(), but the problem is whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop. Is there any way to make sure it takes input only once, regardless of how many lines the user inputs?
The loop breaks if I enter a String. What I want to do is break when only the first input has no more long variables to deal with.
import java.util.Scanner;
import java.io.*;
public class te{
public static void main(String[] args){
Scanner key=new Scanner (new BufferedInputStream(System.in));
String s="";
while(key.hasNextInt()){
System.out.println("Entered loop");
s=s+""+key.nextLong();
}
System.out.println(s);
}
}
Not 100% sure what your trying to accomplish, but to answer this problem:
"..whenever it does not find any more long types, it asks the user to give another input instead of breaking the loop."
I just used a try/catch block. If the input is not a number, it breaks the loop. You can keep inputting numbers and hitting enter, and if an input is not a number, the loop will break; and it will print out the concatenated numbers.
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = "";
System.out.println("Enter Numbers: ");
while (true) {
try {
s += String.valueOf(scanner.nextInt()); // if input is not an int
} catch (Exception ex) { // it will throw exception
break;
}
}
System.out.println(s);
}
}
Edit: Scanning a line
Scanner input = Scanner(System.in);
System.out.printline("Enter some numbers: ");
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextLong()){
long num = lineScanner.nextLong();
// do something with num
}
I encountered an error when executing my program.
I execute my program and fed data in an input file.
Contents of the input file
LIMIT
2
ADD 30 60
MUL -60 60
I got an exception error as follows.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Test.doLimit(Test.java:41)
at Test.checkResult(Test.java:24)
at Test.main(Test.java:15)
I googled and I believed that String input = sc.next(); inside the for loop should be causing the error.
May I know how to resolve this error?
My code is as attached below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
checkResult(input);
}
public static void checkResult(String input)
{
if(input.equals("LIMIT"))
{
//do stuff
doLimit();
}
else if(input.equals("SENT"))
{
//do stuff
}
else
{
//do stuff
}
}
public static void doLimit()
{
Scanner sc = new Scanner(System.in);
int numOfInput = sc.nextInt();
int x,y;
for(int i = 0; i < numOfInput; i++)
{
String input = sc.next();
x = sc.nextInt();
y = sc.nextInt();
if(input.equals("ADD"))
{
//add
}
else if(input.equals("SUB"))
{
//sub
}
else
{
//multiple
}
}
}
You should check if there is more input. You can see in the stack trace that nextInt is involved and if you look at the SDK you would see that this exception is thrown when
input is exausted.
anyway you problem is here :
int numOfInput = sc.nextInt();
so make sure you have valid input before asking for it :
if (sc.hasNextInt()) {
.
.
.
}
The default delimiter of the scanner is the whitespace. However, you plan to use as input for the first 2 lines the new line as delimiter and then either whitespace and new line, as it comes first. Maybe that is the problem. Try writing everything on one line, whitespace separated.
If you are sending the data through the input file, you have to provide that file in the Scanner() constructor.
What you have currently done is provided System.in.
EDIT :
Also, you have to open the Scanner on the file just once and use it throughout. In this case,
1) You are opening the scanner and reading the first line.
2) Then in the doLimit function, you again open the scanner and read the first line of the input file which is not an integer.
Hence, the error.