My goal is to read and print the words separately from standard input, without having to store them in an array or list.
I want this:
input: sun moon cloud
output:
sun moon cloud (each word in a different line)
The following program keep waiting after printing "cloud". I don't know what the problem is
`
import java.util.Scanner;
class RandomWord{
public static void main(String[] args){
String palavra;
Scanner s = new Scanner(System.in);
while(s.hasNext()){
palavra = s.next();
System.out.println(palavra);
}
}
}
`
You continuously reading the scanner.
You have to read by scanner out of loop. For example 3 times invoking s.next().
Or create some loop end condition, for example text, "END".
If you pass all words in one line use .readLine()
Related
I want to print multiple sentences (each having more than one word) in Java but I am getting a run time error even after using .nextLine(). Below is my code, could someone point out what am I doing wrong?
import java.util.*;
class GFG
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); //t>1
for(int p=1; p<=t; p++)
{
sc.nextLine();
String s = sc.nextLine();
System.out.println(s);
}
}
} // Input-
// 2
// HOW ARE YOU
// GOD IS ONE
// Output-
// HOW ARE YOU -(followed by run time error)
The first line in the for-loop: sc.nextLine() reads a line from the in stream and discards it (the return value is not placed into any variable). In your code, you read two lines in every iteration (4 for the provided input) while there are only 2 lines of input. Therefore you need to remove this line (the first sc.nextLine()).
As a side note, when I tried to run the program it just waited for more lines and did not throw a runtime error (also in case you encountered one it's better to post the exception itself).
I started doing the CodeAbbey problems last night, they mentioned using stdIn since some the input data is long so copy/paste is much easier than by hand. I had never used the Scanner before so it looked easy enough. I got it working for single line inputs then I got a problem where the input was:
867955 303061
977729 180367
844485 843725
393481 604154
399571 278744
723807 596408
142116 475355
I assumed that nextLine would read each couple, xxxx yyyyy. I put the code in a while loop based on if nextLine is not empty. It runs, but I get weird output, and only after I hit return a few times.
package com.secryption;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input: ");
Scanner scanner = new Scanner(System.in);
String input = "";
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
String[] resultSet = input.split("\\s+");
for(String s : resultSet) {
System.out.println(s);
}
}
}
I thought I might need something after adding scanner.nextLine() to input. I tried a space and that didn't help. I tried a newline and that didn't make it better.
This "should" put all the numbers in a single array, nothing special. What am I missing with scanner?
EDIT: Ok so #Luiggi Mendoza is right. I found this How to terminate Scanner when input is complete? post. So basically it it working, I just expected it to do something.
The problem is here:
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
Scanner#nextLine reads the line and will continue reading. You're reading two lines and not storing the result of the first line read, just reading and storing the results of the second.
Just change the code above to:
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(" ");
}
hasNext() is an end of file indicator that terminates by combining keys control d on Mac ox and control z on windows pressing enter won't send the right message
to JVM
I'm convinced this is a product of how the string.replaceAll() method works, but for some odd reason its making my loop run twice when you type anything with a space in it?
public class TestCode{
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
String input = "";
while(!input.equals("X")){
System.out.println("Prompt user for input");
input = scan.next().toUpperCase();
calculatePolynomial(input);
}
}
public static void calculatePolynomial(String input){
//Clean up entry removing spaces and extracting polynomial names
String calculation = input.replaceAll("\\s", "");
System.out.println(calculation);
}
}
The idea was to have the code run... printing out the message, prompting input. Then process the input and do some stuff. Repeat the process over and over until the sentinel value 'x' is entered.
But when you type input that contains a space it, for some reason, runs the loop as if each word was now separate input. So if you enter three words, it just runs the loop three times instead of once.
I just want the user's input to be without spaces and without a nightmare of logical errors.
When using a Scanner, by default, next() tokenizes the input by whitespace. So if the user enters two words separated by whitespace, your loop will run twice.
To get the entire input in the user's input line, try using the nextLine() method instead.
I was given the following code and asked to write the Solution class extending from TestList. I wrote a constructor for it (which just called super) and the printSecond2() method invoked in the last line of the code below. All other methods are inherited. Here's the code:
public class Test3A {
public static void main(String[] args) {
TestList tl = new Solution();
tl.loadList();
((Solution) (tl)).printSecond2();//prints every second element
}
}
However, the damn thing was never printing anything out, so I went into the TestList class (which was provided) and put println statements after every single line of the loadList () method:
public void loadList ()
{
if (input.hasNextInt ())//input is a Scanner object
{
int number = input.nextInt ();
loadList ();
add (number);
}
}
I discovered that I can continue to add whitespace, newlines and integers indefinitely, and that the add(number) method is only finally called when I input a character. So if I don't do that, it just sort of hangs around waiting for more input instead of moving on.
I'm confused by this as the provided sample input/output is:
sample input
1 2 3 4 5
sample output
2 4
So there's no character being inputted by the automatic marker.
I have tried overriding the method in Solution (we can't touch the other classes) and:
) changing if to while
) adding an else block
) adding an else if (!input.hasNextInt ())
None of these changed anything. I have no idea how the program is supposed to move on and get as far as calling printSecond2().
Any thoughts? I'd really like to pass my next prac test :D
When user is supposed to enter a sequence of numbers either the number of items should be provided or the input should be terminated in some manner. 1 2 3 and 1 2 3 4 are both valid inputs so scanner can't decide where to end on its own.
It can be assumed that the number sequence is terminated by EOF character Ctrl-Z on windows and Ctrl-D on unix as no other information is given.
There is a way to stop the Scanner at the end of the line. You need to define a delimiter that contains whitespace, the empty expression, but not the next line character:
public static void main(final String[] args) {
Scanner scan = new Scanner(System.in).useDelimiter(" *");
while (scan.hasNextInt() && scan.hasNext()) {
int x = scan.nextInt();
System.out.println(x);
}
}
This way the Scanner sees the \n followed by a delimiter (nothing) and the input stops after pressing return.
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.