How to use multiple Input Dialogs (New to Java) - java

I am trying to create a program that asks a user for a sentinel value (a value to enter when they want to end the list). It then asks the user to enter numbers until they re-enter the sentinel value. It then figures out the max number in the list. I'm very new to Java, and whenever I run the program is just asks for the sentinel value then does nothing else (never pops up the second input dialog). I'm sure it's something simple that I'm doing wrong, but I can't figure it out. Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class HW1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int max;
int sentinel;
int count=0;
JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel=input.nextInt();
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
max = number;
while (number!=sentinel){
count +=1;
if (number>max)
max=number;
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
}
if (count!=0){
JOptionPane.showMessageDialog(null, "The max is:" + max);
}
}
}

You are mixing the ways to input data to your program. Let's begin:
Scanner input = new Scanner(System.in);
The line above allows you to catch data in the command line from the keyboard.
JOptionPane.showInputDialog("Please enter a sentinel value: ");
This Option Pane is showing correctly, you put a value and then nothing happens. This is because your program is waiting to input something in the command line
sentinel=input.nextInt();
When your program arrives to the line above, the input.nextInt() stops the program until you put something in the command line.
The correct way should be something like this:
sentinel = Integer.parseInt(JOptionPane.showInputDialog("Please enter a sentinel value: "));
number = Integer.parseInt(JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" value to end."));
And remove:
number = input.nextInt();
sentinel=input.nextInt();

I think the confusion is this:
the JOptionPane opens with an input dialog
when the option pane closes, whatever you put there is ignored
then the code goes to this line sentinel=input.nextInt();
which waits for input from the console (e.g. you need to go back to the console, type the number there and press enter, only then the program will advance, it will block untill you do)
I would change it to something like this:
String sentinelInput = JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel= Integer.parseInt(sentinelInput);
(repeat for all places where you expect input)
An alternative solution is
Don't use the JOptionPane, and instead just System.out.println to print the user a request for input (instead of the popup dialog). Then you can and keep the existing input.nextInt() calls to collect it.
Just note that all interaction will be in the console, without any popup dialogs (which I actually prefer in terms of user experience, and also it will be working in non GUI machines such as a linux terminal...)

Related

I'm not able to run Java program in IntelliJ IDEA Community Edition

I have written a program that takes input from the input stream but I don't know how to proceed when the program is waiting for input? screenshot added:
Can anyone help please?
There is just one line missing, you need to close the Scanner before you can reach your last System.out.println.
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter two numbers:");
int num1 = in.nextInt();
int num2 = in.nextInt();
int sum = num1 + num2;
in.close(); //This one is important
System.out.println("The sum is : " + sum);
}
}
Then you click into the console and type in your first int --> press Enter and the same for the second int
as can be seen in your screenshot, your program runs and waits for your input, your IDE terminal is printing: "Enter two numbers:" and now is waiting on input due to the next line in your code: int num1 = in.nextInt();. just click on your terminal and see if you can enter an input and click enter on your keyboard, that should do the trick
u need to click on the console and enter param.

While-loop will not terminate in console after entering numbers

I keep trying to get this to work but when I enter in the numbers and enter them into the console it does not finish. I have to terminate myself.
import java.util.Scanner;
public static void main(String[] args) {
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (keyboard.hasNextInt());
System.out.println(outputSum);
}
Well, yes. The keyboard.hasNextInt() call will return false for two reasons.
The next token is a NOT an integer.
You have reached the end-of-input.
What is (most likely) happening is that you have stopped entering numbers. The program is (patiently) waiting for you to enter ... something.
Solutions:
Tell the user to enter the (OS specific) terminal "end of file" character. On Linux it is CTRL-D. On Windows CTRL-Z.
Tell the user to enter something that isn't an integer.
Pick an integer as meaning that there are no more numbers, and test for that.
You also need to instruct the user how to "end" the sequence; e.g.
System.out.println("Enter sequence of numbers. Enter a non-number to stop.");
This is actually a problem with your application's "user interface" design. If the user is expected to type an arbitrarily long sequence of numbers (or something else), then there needs to be some way for the user to tell the program that the sequence is finished. The program cannot magically distinguish the cases of "there are no more" and "hang on, I'm taking a break from typing".
The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
In this case hasNext() won't return true because there is neither any integer nor any whitespace. Therefore the program waits for the next input. Besides use a specific integer to break the loop.
for instance,
System.out.println("Input -1 will end the program!";
do{
int x = keyboard.nextInt();
if(x == -1){
break;
}
//do something
}while(true);
Your code is ok. There is no issue.
But before writing code, we need to think about it. The workflow of your code below:
1st time when we enter do loop, keyboard.nextInt() takes input from us.
Then it calculates the sum and performs string operation.
After that, while's keyboard.hasNextInt() takes next input from you.
Checks your input. If your input is not an integer, while loop will terminate(break).
If your input is an integer then, code loop back to keyboard.nextInt(). But this time, it does not take input from you.
It pases the buffered input(keyboard.hasNextInt()) to keyboard.nextInt() and assign the value to inputNum
So, when you want to terminate while loop, you should input any character like a, b, c, etc.
You haven't specified when the loop will end. Have a condition such as inputting a certain number that will end the program once entered, as currently your program is just going to wait for more input. Something like :
System.out.println("Enter sequence of numbers to add. Enter '0' to end the program");
do {
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
} while (inputNum != 0);//Keeps going as long as 0 is not entered
//When zero is entered, program shows the total sum and terminates
if (inputNum == 0) {
System.out.println("The sum of all total numbers: ");
System.out.println(outputSum);
System.exit(0);//Terminates program
}
Basic syntax of do-while Loop:
do{
// do something
}while(terminating condition);
If you are using hasNextInt() method of Scanner object for terminating condition in do-while loop then loop will be terminated once it get input other than an integer value (e.g float, double, char, String etc.. ) as shown in below complete program.
import java.util.Scanner;
public class Cumulative{
public static void main(String[] args){
int cmlSum = 0;
int inputNum;
String outputSum = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sequence of numbers ");
do{
inputNum = keyboard.nextInt();
cmlSum += inputNum;
outputSum += String.format("%s ", String.valueOf(cmlSum));
}while (keyboard.hasNextInt()); // loop will terminated whenever get any value other than valid integer such as float char or String etc..
System.out.println(outputSum);
}
}

Stuck While Loop (Java)

all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.

Java: Try to Understand Getting Inputs from Users Using Scanner

I have this programs and a few questions regarding to how .next(), .nextInt(), .hasNext() and .hasNextInt() of Scanner class work. Thank you in advance for any of your help :)
import java.util.Scanner;
public class test {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
int age;
System.out.print("Please enter your age: ");
while (!console.hasNextInt()) {
System.out.print("Please re-enter your age: ");
console.next();
}
age = console.nextInt();
System.out.println("Your age is "+age);
}
}
1/ When !console.hasNextInt() is executed for the first time, why does it ask for an input?
I thought at first the console is empty, so !console.hasNextInt() is True (empty is not an int), then it should go directly from "Please enter your age: " to "Please re-enter your age: " but my thought seems to be wrong.
Here, the user needs to enter something before "Please re-enter your age: " is printed.
2/ The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
3/ For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
The java.util.Scanner.hasNextInt() method returns true if the next
token in this scanner's input can be interpreted as an int value in
the default radix using the nextInt() method.
When you start with a non integer input, hasNextInt() will be false and you will enter while loop. Then it will prompt you to re-enter your age. But if you start with integer, you won't enter the loop. Your age will be printed.
console.next() means it takes next input token and returns String. If you write down your code as:
String s = null;
while (!console.hasNextInt()) {
s = console.next();
System.out.println("You entered an invalid input: " + s);
System.out.print("Please re-enter your age: ");
}
console.next() is being used for handling the non-integer inputs. Now, if you enter a non-integer input twenty, you'll see that console.hasNextInt() will be false and console.next() will read it.
hasNextInt() waits for an input string and then tells you if can be converted to an int. With that in mind, let's go over your questions:
When !console.hasNextInt() is executed for the first time, why does it ask for an input?
Because it blocks until there's some input from the console.
The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
Because hasNextInt() returns true when the input can be converted to an int, for example "21".
For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
Calling next() doesn't wait for a new input, it just swallows the input that was tested by hasNextInt() so the scanner can move on to the next one. It could have been the first statement in the loop, with the same effect.

Basic program hanging at nextInt()

I have just started my 2nd programming course at college and our first assignment is rather simple, intended to basically check our environment and to check we know how to submit assignments through the course website.
When I run the code we have been supplied with, it hangs where it is supposed to prompt for the user to enter a number, so that it can print it. I inserted a series of println statements to determine where it was hanging.
It prints TEST1, TEST2 and TEST3, but never makes it to TEST4. So there must be something wrong with the line:
number = input.nextInt();
But I can't for the life of me see what's wrong with that line. Any help would be greatly appreciated! :)
Anyway, here is the code
package rossassignment1;
import java.util.Scanner; // use the Scanner class located in the "java.util" directory
public class RossAssignment1 {
public static void main (String[] args) {
System.out.println("TEST 1");
int number;
System.out.println("TEST 2");
Scanner input = new Scanner(System.in);
System.out.println("TEST 3");
number = input.nextInt();
System.out.println("TEST 4"); // display the number with other messages
System.out.print("This program reads an integer from a keyboard,\n"
+ " and print it out on the display screen.\n"
+ "The number is: " + number + ".\n"
+ "make sure that you get the exact same output as the expected one!\n");
}
}
After the line input.nextInt() is run the program is waiting for the user (you, or whatever marking system is being used) to input an integer in the console. After you do so the program will continue to your TEST4 line.
If after entering an integer, the codes after that still don't show up, you can do this:
number = input.nextInt();
input.nextLine(); //Add this
It will clear the newline.
Alternatively, I prefer to do this:
number = Integer.parseInt(input.nextLine());

Categories

Resources