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.
Related
So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me.
One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.
Here is the code:
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for (i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below:
I have also included a screenshot of the code from the book below:
I was wondering whether anyone knows why this is the case!
Any help would be greatly appreciated thanks.
The reason it's printing multiple times is because multiple characters are detected.
In your case, it's printing twice because you entered a value (Pass 1) and a new line (Pass 2)
The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.
So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using
This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.
The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.
in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.
It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.
I'm trying to make a tic-tac-toe game and I'm encountering a lot of copy-paste work for inputs. I'm trying to figure out what design pattern and implementation works for prompting the user, collecting their input, comparing it and then acting by assigning a value. Right now my code looks like this.
public void promptPlayerCount(BufferedReader in) throws IOException {
String input;
// initial prompt
System.out.println("How many players?");
input = "try again";
while (input.equals("try again")) {
input = in.readLine();
// extract data and check it
switch (Integer.parseInt(input)) {
case 1:
// assignment
playerCount = 1;
break;
case 2:
playerCount = 2;
break;
default:
input = "try again";
// clarified instructions
System.out.println("please enter 1 or 2");
}
}
}
There's a part of me that thinks I could make a function (maybe a factory?) that allows me to generate a function by passing the constructing function the details of the initial prompt, the extraction method, the assignment action and the clarification message.
Would this be best done with lambda functions?
Text input is hard, especially if you can't trust your user (like in a game). Your parseInt will throw a nasty exception right off if your value isn't an integer.
Also standard in is not friendly. I assume this is for an assignment so I won't fault you for using it, but in anything where you don't HAVE to use stdin, don't. The problem is that it's amazingly difficult to get Java to respond to anything less than an entire line with an enter at the end.
When dealing with user input I almost always trim it (Just because they love to insert random white spaces at the beginnings and end) and check to see if it's empty. This could probably be put into a function that also either shows an error or exits the program on "Empty" and otherwise returns a string.
If you often want int values, write a second function that calls the first. Have the second function return an int, but have it catch the exception if the text is invalid and prompt the user again. You could even have this function take a "Range" of integers as a parameter and provide a prompt. So what you have above could look like this:
playerCount = getUserInput("Please enter the number of users", 1, 2);
The rest is wrapped in simple non-redundant functions.
Won't write the code for you because A) it's probably a homework assignment and the fun part is actually coding it and B) someone else probably will provide a full solution with code before I'm done typing this :(
Good luck.
package happy;
import java.util.Scanner;
public class PiVal {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in); //initialise scanner
String val= Double.toString(Math.PI); //Storing PI to string
System.out.println(val);//Printing the stored value
System.out.println("Enter the value");//Screen output to print
int till =s.nextInt(); //taking user input storing in till
till+=2; //increasing value to +2 as only want to change after decima
if(till>15) //Checking if variable value more than 15
{
System.out.println("Out of bounds");
}
System.out.println(val.substring(0,till));
s.close();
}
}
My code looks like this very simple code i know just revising some stuffs but the thing i am not able to get my head around is why i need to input 2 times just to run the code and the "Print " command is not running very first it is running after the scanner input.
OutPut looks like this
8
8
3.141592653589793
Enter the value
3.14159265
Edit:
Eclipse LUNA
Seeing that the code produces the correct output for everyone else, there is something wrong with your IDE. Try running your program in another IDE and see if that helps. You should update Eclipse Luna(if any updates are available) and restart it(just quit and reopen). That should solve your issue, however if it does not, You may need to use a different Environment.
Refer to this link dude. It's always recommended by the developer of eclipse to use the most updated version of eclipse. But of course, it's not necessary all the time. However, luna is using version 4.4, while the second latest eclipse is already using 4.6 which is ahead by at least 2-3 years.
What you're facing could be some issues that no one really has officially brought up before. It's just how certain IDE works behind which programmers like us may not understand. It's similar to Quincy who doesn't follow the correct order during program runtime.
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.
My class got a Java programming project today in class and the program we are using is jGrasp, I know that I can handle the pieces of this project except for one aspect.
The project requires the user to enter data into the program (i.e. answer a question), but for this Semester we are not using GUIs so I can't create a GUI for the user to input the data or answer.
I'd like to know how could the user enter data into jGrasp without using a GUI?
Thanks for taking the time to read this post, and I'd greatly appreciate any help you could give me.
I hope I'm helpful :) it's funny that I want to know about the same thing in GUI & you want to know without it :D ....well i can solve your matter I believe :)
From the starting,
Example:
import java.util.*;
public class Assignment //class name
{
static Scanner stdIn = new Scanner(System.in);
public static void main(String[]args)
{
int A, B; //Intialize variables as normal
System.out.print("Enter a question you want to ask "); //Between the double quotes " " you type anything you want to type :)
A = stdIn.nextInt();
: //
: // complete your program
System.out.println("Add the statement for giving the result "+B); // "+B" for inserting the answer along with your result statement
}
}
Note: In the statements,
System.out.print();
System.out.println();
These statement work similarly.... just the difference is statement with "print" is displayed on the same line & Statement with "println" is displayed in next line....when you will try you will understand ...just for avoiding confusion why I have written so I'm mentioning it :)
I hope this helps...tczz :)