How to read float input without knowing size in java? - 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.

Related

Continuous Scanner input

I'm writing sort of main practice project, where I can just continually add classes that do completely different fun things. For example, I have a CoinFlipperCmd and a poker PotOddsCmd, and the code currently works fine, but I want to be able to repeatedly enter commands without having to rerun the program. Example console currently:
FLIP 10 // coinflips 10 times and notes the outcome
You flipped 5 heads and 5 tails
After this, the code will exit, but I want to be able to keep entering commands. Like so:
FLIP 5
You flipped 4 heads and 1 tails
FLIP 6
You flipped 3 heads and 3 tails
POTODDS 0.5 1
You have pot odds of 2:1
I'm using a scanner for input
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args) {
InputScanner();
}
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter command");
String command = myObj.nextLine(); // Read user input
ParseAndDirect(command);
}
private static void ParseAndDirect(String command) {
String[] commandSplit = command.split(" ", 2);
String usercommand = commandSplit[0];
if (usercommand.equals("FLIP")){
CoinFlipperCmd.CoinFlipperCmd(commandSplit[1]);
} else if (usercommand.equals("POTODDS")){
PotOddsCmd.PotOddsCmd(commandSplit[1]);
} else System.out.println("Invalid Command");
}
}
You need to put the input part inside a loop e.g.
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String command;
do {
System.out.print("Enter command (q to quit): ");
command = myObj.nextLine(); // Read user input
if (!command.equalsIgnoreCase("q")) {
ParseAndDirect(command);
}
} while (!command.equalsIgnoreCase("q"));
}
Another way of using the loop can be as follows:
private static void InputScanner() {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String command;
while(true)
System.out.print("Enter command (q to quit): ");
command = myObj.nextLine(); // Read user input
if (command.equalsIgnoreCase("q")) {
break;
}
ParseAndDirect(command);
}
}
On a side note (because it won't have any impact on the execution of the program), you should always follow Java naming conventions e.g the method, ParseAndDirect should be named as parseAndDirect and InputScanner should be named as inputScanner.
Apart from allowing the user to repeatedly enter commands, I think you should also allow some way to quit the program (besides having to kill it via the operating system :-) In the below code, I have arbitrarily used the word quit as the way to exit the loop. Feel free to use a different string.
Scanner myObj = new Scanner(System.in);
String command = "";
while (!"quit".equalsIgnoreCase(command)) {
System.out.println("Enter command");
if (!"quit".equalsIgnoreCase(command)) {
ParseAndDirect(command);
}
}
By the way, according to java naming conventions the method name should be parseAndDirect, i.e. it should start with a lowercase letter.

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.

How to stop printing input at 42?

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);
}
}

Problem in looping when using method in Java

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.

Reading inputs in java

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.

Categories

Resources