I am trying to write program to called Triangle.java. The program should read 3 Integers from file as standard input and use them as parameters.
I did something like this:
Scanner input = new Scanner(System.in);
while(input.hasNextLine()) {
String TestName = input.nextLine();
int x = input.nextInt();
int y = input.nextInt();
int z = input.nextInt();
.......
}
and then I wanted to use x,y and z as parameters. I tried to compile the program on my ubuntu machine using command line javac Triangle.java<test.txt then run program using java Triangle.class.
Things do not seem to be working. Any suggestion would be highly appreciated.
Okay, a couple of problems with that code, but here's your main problem: You read more than you have
String TestName=input.nextLine();
int x =input.nextInt();
int y =input.nextInt();
int z =input.nextInt();
input.nextLine() will already read the ENTIRE line. So input.nextInt() will try to read ints from the next line yet again of which you don't even know if it exists.
That's not so much a problem with System.in because it will just prompt the user to enter some more ints (though I don't see how the TestName variable will be of any use anyway). But if you're using a file, this will become a problem.
Also, as a side note:
You can't really call input.hasNextLine() on a Scanner using System.in, because at that point in time, there will be no next line in the input stream. You first have to prompt the user to input some more before there will be a line, which means your while will never be executed.
However when you're using a file, obviously the check will work, so you should keep it around anyway.
Related
I want to output a question to the console and then get the next line of input after the question was output.
For example, my program could be sleeping or doing some time-consuming computation, and while the user is waiting they might decide to type some notes into the console (perhaps without hitting enter, or perhaps over several lines). Once the sleep is completed, the program then asks the user a question, "What is your name?" and then it should wait for the next line of input containing the user's name, and ignore any random notes the user made while the sleep was going on.
Here's some code that tries to do that:
public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
Thread.sleep(10_000);
System.out.println("What is your name?");
// while (scanner.hasNext()) {
// scanner.nextLine();
// }
String name = scanner.nextLine();
System.out.println("Hi, " + name);
}
This behaves as follows when I type a couple of lines during the sleep:
gpeo
hpotWhat is your name?
Hi, gpeo
The problem is that scanner will read the next input continuing from the last input it read, not from the last System.out.println() (which makes sense). The commented out code tries to rectify that problem by reading past all earlier input first, then waiting on one more line to assign to name. However, scanner.hasNext() does not work as I was hoping, since when there is no next token it does not simply return false but waits for another token (so I don't know why it bothers to return a boolean at all).
Another thing that baffles me is that during the sleep if you type stuff on a single line, that single does in fact get ignored:
brbr irgjojWhat is your name?
A
Hi, A
I thought it was going to output Hi, brbr irgjojA, so that makes me think I might be misunderstanding how console input and Scanner work.
Edit: The last example was from a run within IntelliJ. When I run from my Bash commandline instead I get Hi, brbr irgjojA. The output of the first example does not change though.
Also, I was asked if this question is the same as this, and apparently I have to explain why it's not here or it will appear on the question. The issue in that post (and others like it) is that he/she is mixing scanner.nextLine() with scanner.nextInt() and similar methods that do not read the whole line or the line ending. I am only using nextLine() to read input, and my issue is quite different.
Further edit
I managed to discard the first line of random notes based on this answer to another question. Here is the new code:
public static void main(String[] args) throws InterruptedException, IOException {
Scanner scanner = new Scanner(System.in);
Thread.sleep(10_000);
System.out.println("What is your name?");
while (System.in.available() > 0) {
scanner.nextLine();
}
String name = scanner.nextLine();
System.out.println("Hi, " + name);
}
Here are some test runs in IntelliJ:
grgWhat is your name?
A
Hi, A
ghr
rhWhat is your name?
A
Hi, A
rghr
hrh
htWhat is your name?
Hi, hrh
uirh
iw
hjrt
sfWhat is your name?
Hi, iw
And here are similar tests in Bash:
htrWhat is your name?
A
Hi, htrA
rgj
hrWhat is your name?
A
Hi, hrA
rjkh
ry
jWhat is your name?
Hi, ry
ryi
rj
rd
jrWhat is your name?
Hi, rj
As you can see, the line inside the while loop never appears to get executed more than once for some reason. I tried adding a sleep inside the loop or using other InputStream methods like skip() and readAllBytes(), but these didn't seem to help at all.
I think there might not be anything one can do about the incomplete line that is a problem for Bash, but I'm sure there must be a way to throw out all the completed lines (rather than just the first one). The solution doesn't have to use Scanner, it should just behave as intended.
The Scanner uses a buffer. It’s default size is 1024 characters. So by the first nextLine() call, it reads up to 1024 of the available characters into the buffer. This is necessary, as the Scanner doesn’t even know how many characters belong to the next line, before filling the buffer and searching for a line break in the buffer.
Therefore, if there are less pending characters than the buffer size, the loop will iterate only once. But even when there are more characters, and more loop iterations, the resulting state likely is to have some pending lines in the buffer.
As long as the Scanner’s buffer is in its initial empty state, you can flush the source stream directly, instead of using the scanner:
Scanner scanner = new Scanner(System.in);
Thread.sleep(10_000);
while(System.in.available() > 0) {
System.in.read(new byte[System.in.available()]);
}
System.out.println("What is your name?");
String name = scanner.nextLine();
System.out.println("Hi, " + name);
Note that it would be natural to use System.in.skip(System.in.available()); instead of read, but while trying it, I encountered a bug that the underlying stream did not update the available() count after a skip when reading from a console.
Note that if the Scanner is not in its initial state but has some buffered content already, there is no way to flush the buffer, as its API is intended to make no distinction between buffered and not yet buffered, so any attempt to match all content would result in reading from the source (and blocking) again. The simplest solution to get rid of the buffered content would be
scanner = new Scanner(System.in);
public class UseVariableValueAgain{
public static void main(String args[]){
int x=6;
int y=7;
int LastValue=0;// for first time
LastValue=x+y+LastValue;
System.out.println("result"+LastValue);
Scanner scan = new Scanner(System.in);
int x1=scan.nextInt();
int y1=scan.nextInt();
int LastValue1=0;
LastValue1=x1+y1+LastValue1;//for first time
System.out.println("REsult using Scanner="+LastValue1);
}
}
Ressult=13
5
6
Result using Scanner=11
when i execute this program i got 13 output by default and by using scanner
i enter 5,6 and output is 11 , Now I want to use (13,11)values for next
time when i re-execute the program. but it give same result
Your options in order of easiness:
1) Next time when you invoke the program, pass the values at the command line.
java UseVariableValueAgain 13 11. You will have access to these values via args[] array now. Keep in mind you will have to parse this to integer as args is a String array.
2) Write these values to a file. (eg using BufferedWriter) and read it in the program using Scanner or BufferedReader;
3) Write the value to a database table. Read the values from the table in your program.
In all these options, you will have to check if this is a re-run by employing appropriate if-else conditions to check if the value needs to be read from user input or if it needs to be determined.
If you are learning Java, I recommend trying all three options in that sequence.
You need to write the previous value in a persistent storage(like file).
I've been searching overflow questions and googling it for about half an hour and can't find an answer for this.
At first I thought it might be that I'm not closing my Scanner object. I added
inp.close();
after all my code,but still nothing.
I'm using Eclipse to create a simple Binary Search algorithm.
My problem is that it is not keeping my input. And what's even weirder is that it only accepts "5".
After pressing enter it only creates more spaces. It doesn't move on to the rest of the program.
I've also tried entering more values under the "skipped" ones without any success.
Here's some screenshots
nextInt() reads scans the next token of the input as an int.
If the input is not an int, then an InputMismatchException is thrown.
You can use next() to read the input, whatever its type is. And you can hasNextInt() to make sure the next input is an int:
Scanner inp = new Scanner(System.in);
if(inp.hasNext()) {
if(inp.hasNextInt()) {
int n = inp.nextInt();
// do something with n
} else {
String s = inp.next();
// do something with s
}
}
Actually, I have a theory - your Scanner code is working just fine, it's your binary search code that's broken. Whatever it's doing works on an input of 5 but falls into an infinite loop for other inputs.
Consider breaking up your input parsing code from your binary searching code (e.g. do input parsing in main() and define a binarySearch() function that main() calls) so that you can test them separately.
First I'm a noob to Java so don't be mad at me if I'm acting stupid - Thanks.
As I said I'm trying to learn Java. Right now I'm trying to learn the right scanner for this mini-game, but I'm getting confused because people tell me to do it in two different ways. I just wan't to know which one to use and where I can use the other one.
First Example:
Scanner input = new Scanner(System.in);
Second Example:
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
Please tell me how to make the " right " scanner for my mini-game and explain when I should use the other one.
If you know which one to use, another way to create a scanner for this or just wanna share the scanners and how to use them - then please add it as an answer.
Scanner input = new Scanner(System.in);
This is calling a scanner and telling that it should be used in the console "System.in".
String userInput = input.nextLine();
This line is taking the value u inserted in the console and saving in a variable named "userInput"
You can add this System.out.println("the inserted value is : " + userInput);
And it will print in the console the value you inserted
If I'm reading your question correctly, both of your examples are same as far as creating a Scanner object is concerned. Only difference is that second example is also storing the nextLine of input into a String variable called userInput.
Look here to understand Scanner class better:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I've just started learning Java (I am a C#.NET programmer as well). I am trying to get multiple user inputs and add them to an array. After this, I calculate the average from the given values.
For some reason, BlueJ will try to run my Java program forever. Meaning, It will keep showing the progress bar and will not open any console window.
I'm not sure if it's something wrong with my code, or BlueJ, because I've never encountered a problem such as this one before.
Here is my code:
import java.util.Scanner;
public class Problem22 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int inputs = 2;
int[] values = new int[3];
while (inputs > -1) {
values[inputs] = scanner.nextInt();
inputs--;
}
System.out.println(averageValue(values));
}
private static int averageValue(int[] values) {
int sum = 0;
for (int i : values) {
sum += i;
}
return (sum / values.length);
}
}
Please help me try and find a solution.
It seems that in BlueJ, you have to supply output before you ask for input. It's quite a weird bug.
More info:
http://www.bluej.org/help/faq.html#hangoninput
Your code worked for me in Eclipse, but I had to realize what I was supposed to do, enter three ints.
It is generally better to prompt the user for input. This may be a bug in BlueJ, but it's not too bad to have to output a prompt before asking for input. It's just generally a good thing to do.
Link to my version of the code with prompts:
https://gist.github.com/kaydell/6552282
I believe that the only reason not to prompt for input is if you are reading input from a file or something. When your program is interactive with the user, your programs should prompt the user for input.
The code compiles just fine for me in IntelliJ IDEA, and also runs fine. so I would assume it's a BlueJ bug.
Here is an example input and output after running it (pressing enter after each input line)
3
4
5
4
(which means by the way your code works correctly, 4 is the average of 3,4,5...)
Which version of BlueJ are you using? I assume restart to BlueJ or even your machine didn't work?
Terminal window opens only when there is an output. Th program has asked only for input. Therefore it is terminal window isn't opening. Replace your snippet by this one:
`while (inputs > -1)
{
System.out.println("Input number - "+inputs);
values[inputs] = scanner.nextInt();
inputs--;
}`
I hope you will see the terminal window.