Hello everyone I'm trying to improve my Java skills by solving some problems from ACM, now the thing is my sample input looks like this :
3 100
34 100
75 250
27 2147483647
101 304
101 303
-1 -1
So at first I'm just trying to read them but its not working here is the java code:
import java.io.BufferedInputStream;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
System.out.println(stdin.nextInt() + " and the next " + stdin.nextInt());
}
}
}
I'm trying to send these inputs as an argument, and not by reading them from file, here is how:
The program just spins(executes) but not printing anything. How can I fix this?
The arguments you have specified in your wizard are not input to the program via std in. Instead, they are passed in in the String[] args arguments passed into your main method. As it looks as though you are running in Eclipse, you can go to the Console tab that gets generated and type into that window. Alternatively, you can iterate over the args param to get those values.
I am not using Eclipse, but this should print the numbers you have inputed.
You are passing the numbers as string arguments, so this: "3 100" is actually equal to
String str = 3 + " " + 100;
This should print the numbers:
public static void main(String[] args)
{
for (String arg : args)
{
System.out.println(arg);
}
}
Try this:
Scanner sc = new Scanner (System.in);
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
After you start the program you should provide some numbers as an input.
Related
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.
The following program is to display the word with maximum number of vowels.But it does not work until i have given 10 variables as input even though it is supposed to end after giving a null input.How can I fix this problem ( I already tried using different inputs like "." and " ")
**
import java.util.*;
public class hw1{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String w,temp="";
int c=0,max=0;
for(int i=0;i<10;i++)
{
w=sc.next();
w=w.toUpperCase();
if(w.equals(""))
break;
for(int j=0;j<w.length();j++)
{
if(w.charAt(j)=='A'||w.charAt(j)=='E'||w.charAt(j)=='I'||w.charAt(j)=='O'||w.charAt(j)=='U')
c++;
}
max=Math.max(max,c);
if(max==c)
temp=w;
c=0;
}
System.out.println(temp);
}
}
**
sc.next()
does not trigger if you give empty input (or press enter).
For allowing your exit condition to work you should use
w=sc.nextLine();
After that, if you hit enter, the for is broken and the app prints the result
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);
}
}
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.
I'm doing a simple program regarding methods.
But I have one problem. Everything is already working except when looping.
When I choose to loop again. The program skips on inputting the name. And proceeds directly to the year and section.
Here's the code:
public static void main(String[] args) {
do{
System.out.println("Input info:");
name=stringGetter("Name: ");
yearandsec=stringGetter("Year and section: ");
sex_code=charGetter("Sex code: " + "\n" + "[M]" + "\n" + "[F]:");
scode=intGetter("Scholarship code: ");
ccode=intGetter("Course code: ");
units=intGetter("Units: ");
fee_per_unit=doubleGetter("Fee per unit: ");
misc=doubleGetter("Miscellaneous: ");
display();
switches(scode, units, fee_per_unit, misc);
System.out.println("Another?");
dec=rew.nextInt();
}while(dec==1);
}
Here's the method getting the value for name together with the year and section:
public static String stringGetter(String ny){
String sget;
System.out.println(ny);
sget=rew.nextLine();
return sget;
}
I'm really annoyed with this problem, and I don't have any idea on how to fix this. Please help. thanks
Here is a simpler and more complete program that reproduces the error:
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
int dec;
do {
System.out.println("Input info:");
String name=stringGetter("Name: ");
String yearandsec=stringGetter("Year and section: ");
dec=rew.nextInt();
} while(dec==1);
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
The problem is that after calling nextInt() the call to nextLine() reads up to the new line after the int (giving a blank line), not up to the next new line.
If you change dec to a String and change dec=rew.nextInt(); to dec=rew.nextLine(); then it will work fine. Here is a complete example that you can copy and paste into a blank file to see that it works correctly:
import java.util.*;
public class Program
{
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
String dec;
do {
System.out.println("Input info:");
String name = stringGetter("Name: ");
String yearandsec = stringGetter("Year and section: ");
dec = stringGetter("Enter 1 to continue: ");
} while(dec.equals("1"));
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
}
You may also want to consider adding proper parsing and validation to your program. Currently your program will behave in an undesirable way if the user enters invalid data.
The line:
dec = rew.nextInt();
Is reading an int value from the input stream and is not processing the newline character, then when you come back to point where you get the name at which point a new line is still in the Reader's buffer and gets consumed by the stringGetter returning an empty value for name.
Change the line to do something like:
do {
//....
s = stringGetter("Another (y/n)? ");
} while ("y".equals(s));
Well you haven't told us what "rew" is, nor what rew.nextInt() does. Is it possible that rew.nextInt() is waiting for the user to hit return, but only actually consuming one character of the input - so that the next call to rew.nextLine() (for the name) just immediately takes the rest of that line? I suspect that's what's happening because you're using System.in - usually reading from System.in only gives any input when you hit return.
(It's possible that this is also only a problem on Windows - I wonder whether it consumes the "\r" from System.in as the delimiter, leaving "\n" still in the buffer. Not sure.)
To test this, try typing in "1 Jon" when you're being asked whether or not to continue - I think it will then use "Jon" as the next name.
Essentially, I think using Scanner.nextInt() is going to have issues when the next call is to Scanner.nextString(). You might be better off using a BufferedReader and calling readLine() repeatedly, then parsing the data yourself.