How to stop printing input at 42? - java

I'm doing a problem on a website where it inputs the numbers:
1
2
88
42
99
and it's supposed to output
1
2
88
The code is supposed to stop printing the input when it hits 42, and it works, but when I submit it to the site, it tells me that it gave the wrong answer.
Here's my code:
http://pastebin.com/y5e8DyHz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int res;
for(int i=0;i <5; i++) {
res = scan.nextInt();
if (res!=42) {
System.out.println(res);
} else {
System.exit(0);
}
}
}
}
It works when I run it in IDEOne, so I'm not sure what the problem is. Thanks!

Note that a solution to the TEST problem is available in the SPOJ forums. It's a good example of how to process input as fast as possible in java.

Based on your requirement, you have to use it like shown below, even in your IDE
Scanner scan = new Scanner(System.in);
int res;
while (scan.hasNext()) {
res = scan.nextInt();
if (res != 42) {
System.out.println(res);
} else {
System.exit(0);
}
}
Reason being what #jrbeverly mentioned above as his comment
update 1:
If you meant "stop printing the input" as the program must exit on encountering '42',you are good. But if your requirement is just to discard printing the number, and let the program run and accept the next number, then remove System.exit(0) . because System.exit(0) means to terminate the JVM from further execution of the program
update 2:
As #Giovanni Botta mentioned below, the exact solution is provided in the mentioned link, snippet adding here
public class Main
{
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);
}
}

Related

How to read float input without knowing size in java?

Sample Input:
9.1 9.0 8.9 8.8 9.4 7.9 8.6 9.8
Here is my code for getting input.
I dont know how to get this type of input without knowing the number of inputs.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class Diving_Competition {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
lst.add(in.nextFloat());
}
System.out.print(lst);
in.close();
}
}
This loop runs infinite time. How to get input in a single line without knowing its size?
I'm from python background
As long as there are numerical inputs, your code will not exit the while loop because the condtion in.hasNextFloat() is satisfied.
Assuming you are entering the sample in the terminal: To exit the loop, just enter any non-numerical value like a or enter the EOF-command. In Unix this is Ctrl+D and in Windows it is Ctrl+Z (not sure about Windows-Command)
Haven't java in a bit but I think this works. I read the whole line and separate them.
import java.io.*;
import java.util.*;
/**
* Diving_Competition
*/
public class read {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String string = in.nextLine();
String[] stringLst = string.split(" ");
ArrayList<Float> numLst = new ArrayList<Float>();
for (String num : stringLst) {
numLst.add(Float.parseFloat(num));
}
System.out.print(numLst);
in.close();
}
}
The best way to figure out such issues is either by debugger OR use console to print helpful information. Your program is perfectly fine, it hangs because it is expecting an input that needs to be entered (unless you want to scan input as program args then its a different question).
Here I made a simple change in your program
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
ArrayList<Float> lst = new ArrayList<Float>();
while (in.hasNextFloat()) {
float x = in.nextFloat();
System.out.println("Number Entered: " + x);
lst.add(x);
}
System.out.print(lst);
in.close();
}
and here is console output
2.3
Number Entered: 2.3
re
[2.3]
Notice how to end the input, I had to enter non-float letters. If I don't enter that, the program will continue to take input from the console, one-by-one.
That being said, from your question it looks like you want to get a line of float input from console. If that the case, then you should read by line and parse it based on "space" character.

Program that returns input \t as *

The code is supposed to read an unidentified number of inputs from the keyboard and return any tabs as *. My program seems to work when I run it in eclipse and get no errors. When I turn in the code on the submission website, this is the error I get.
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1589) at replaceHW.main(replaceHW.java:9)
import java.util.Scanner;
public class replaceHW {
public static void main(String[] args) {
//write a program that converts all TABS in your code
//with STARS i.e. *
Scanner in = new Scanner(System.in);
String ans;
while(!(ans = in.nextLine()).equals(""))
System.out.println(ans.replace("\t","*"));
}
}
Your problem is simple: nextLine() works in tandem with hasNextLine(): the correct code is:
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!"".equals(line)) {
System.out.println(ans.replace("\t","*"));
}
}
The try-with-resources is best practice. But be wary than with System.in, it will close it when done.
hasNextLine() will try to read has much input is needed to find a line.

I am getting a runtime error in this code written in java. Kindly check the mistake ill send the error too

/* package codechef; // don't place package name! */
import java.util.*; import java.lang.*; import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef {
public static void main (String[] args) throws java.lang.Exception {
int x=0,y=0,b,z=0,ctr=0,c;
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); String s = buf.readLine();
System.out.println("Enter No. of Test cases");
int a = Integer.parseInt(s);
int arr[] = new int[a];
if(a>=1 && a<=1000)
{
for (x=0;x<=a-1;x--)
{
System.out.println("Enter the cases");
arr[x]=Integer.parseInt(s);
}
}
for(y=0;y<a;y++)
{
if(arr[y]>=1 &&arr[y]<=1000000 )
{
c= arr[y];
b=a*2;
for(z=1;z<a;z++)
{
if(z==1||z==2||z==a)
{
if(b%z==0)
{
ctr++;
}
}
else
{
if(b%z==0)
{
ctr++;
}
}
if(ctr>3)
{
System.out.println("Sorry");
}
else
{
System.out.println("lucky Number");
}
}
}
} }
}
Your code has a few issues. Not sure what you are trying to do with this, but first thing I noticed is that you probably want to put your System.out.println before you read from System.in.
As you have it written, it will wait for the user to enter a number without prompting for it. Move System.out.println("Enter No. of Test cases"); above the BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); line. That way it will prompt for the number of test cases before reading it from System.in.
The next thing I notice is that your indexing on the first inner for loop is wrong, which is resulting in an ArrayIndexOutOfBounds exception. In your first for loop, on the inner loop you have for(x=0;x<=a-1;x--). You are decrementing your index variable x where you want to increment it. Changing that inner for loop to for(x=0;x<=a-1;x++) will get rid of the ArrayIndexOutOfBounds exception.
As for the rest of your code, I'm not sure what you are trying to do, but it executes without error once you fix the ArrayIndexOutOfBounds exception.

Copied this exact code from my book and does not work

I copied this exact code from my textbook, and when I try to run it it does nothing but load, the file is in the same location of the java file, and the name is correct. Im using Dr. Java. So im just wondering why it wont run and just keeps loading. The book I am using is Java Illuminated 3rd edition. Also, the newscores.txt file just has 10 numbers, seperated by spaces.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class TestScoresAndSummaryStatistics {
public static void main(String[] args) throws IOException {
int number;
File inputFile = new File("newscores.txt");
Scanner scan = new Scanner(inputFile);
while (scan.hasNext()); {
number = scan.nextInt();
System.out.println(number);
}
System.out.println("End of file.");
}
}
you have a semicolon end of while statement .you should remove it.because of this semicolon your while loop run repeatedly and your code inside while loop become separate block from the loop.
while (scan.hasNext()); {
number = scan.nextInt();
System.out.println(number);
}
change to
while (scan.hasNext()) {
number = scan.nextInt();
System.out.println(number);
}

Can't print line after looping through scanner input - Java

Why does this not print 'done'?
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
System.out.println(s.nextInt());
}
System.out.println("done");
}
}
It prints the input just fine, but doesn't print the word done.
EDIT if I input integers separated by space in the console and then hit enter, it prints all the integers I entered on a separate line, but it just doesn't print the word done after all that
EDIT
this works… but seems not very elegant
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int temp;
while (s.hasNext()) {
temp = s.nextInt();
if (temp != -99) {
System.out.println(temp);
} else {
break;
}
}
System.out.println("done");
}
}
What you are seeing is that Scanner is blocking on the input stream where there are no characters, and is just waiting for more. To signal the end of the stream, the 'end of stream' character has to be sent. That is ctrl-d on linux.
From the documentation of java.util.Scanner (http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html).
Both hasNext
and next methods may block waiting for further input. Whether a hasNext method
blocks has no connection to whether or not its associated next method will block.
For example, from a linux command prompt
> javac Main.java
> java Main
> 810
810
> 22
22
> foo
java.util.InputMismatchException
> java Main
> 1
1
> ctrl-D
done
Another way to test this is to echo a line or cat a file into your program:
> echo 2 | java Main
2
done
EDIT:
Given the desired outcome described in the comments below; Give the following a try, it will read in only one line. Parse the space separated ints out, echo them one per line and then print done.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
*
*/
public class Main {
public static void main(String[] args) throws IOException {
String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
Scanner s = new Scanner(str);
while (s.hasNext()) {
System.out.println(s.nextInt());
}
System.out.println("done");
}
}
EDIT EDIT: Cleaned up the answer and worked in information from the comments.

Categories

Resources