I am not sure why this code is not working.
I am suppose to have another dialog box appear after the user selects yes or no, but whenever I run the program, it asks for y or no and then nothing happens after.
Any ideas on what I need to do?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int max = 0;
int min = Integer.MAX_VALUE;
String number;
boolean yn = true;
do {
number = JOptionPane.showInputDialog("Please enter a number");
int num = Integer.parseInt(number);
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
System.out.println(min + " " + max);
JOptionPane.showInputDialog("Would you like to enter another number? (y/n)");
String ny = in.nextLine();
if (ny.equals("n")) {
yn = false;
}
JOptionPane.showInputDialog(ny);
} while (yn == true);
JOptionPane.showMessageDialog(null, "The max number is " + max + " and the mininum number is " + min);
}
}
The program stops on
String ny = in.nextLine();
waiting for input from System.in based on the Scanner defined on the first line.
If you enter 'n' on the console and press enter then the program carries on and shows the next dialog box.
I guess you meant to say:
String ny = JOptionPane.showInputDialog("Would you like to enter another number? (y/n)");
The issue you are having is that you are not accepting the input from the panel, and are instead taking it from the console. To solve this, set ny to be equal to the input from the JPane, like so:
String ny = JOptionPane.showInputDialog("Would you like to enter another number? (y/n)");
However, there is another issue, which is this line:
JOptionPane.showInputDialog(ny);
It creates a pane that you don't need that displays y or n, and doesn't accept input. This line doesn't need to be there, so you should remove it. Your code works fine otherwise.
Related
Question 2:
As the code is written, if the use inputs a valid integer it asks for "Enter number 2", then "Enter number 3", then sums them. If the user inputs any data other than an integer for any of the entries, the code will print out "Invalid number entered" and only sum the valid integers entered. What I would like to do is force the user to enter only valid integers and the code remain repeating "Enter number X" for that entry until the user does so. Could someone please let me know how this is done? Thanks. Ron
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int counter = 0;
int addSum = 0;
while (counter < 3) {
counter++;
int numberEntered = 0;
System.out.println("Enter number " + counter + " :");
boolean hasNextInt = myScanner.hasNextInt();
if (hasNextInt) {
numberEntered = myScanner.nextInt();
// myScanner.nextLine(); //why can't myScanner.nextLine()
// could go here right after the number entered
// is captured and stored in the numberEntered variable;
addSum = addSum + numberEntered;
} else {
System.out.println("Invalid number entered");
}
// myScanner.nextLine only works if placed here before
// closing of the while loop;
myScanner.nextLine();
}
System.out.println("The sum of the numbers entered are " + addSum);
myScanner.close();
}
}
Right now, you are always incrementing the counter no matter what:
while (counter < 3) {
counter++;
Even when the user enters an invalid number, you increment the counter, causing the loop to run 3 times as usual, hence the current behaviour.
You should only increment the counter when the user enters a valid number:
if (hasNextInt) {
counter++;
numberEntered = myScanner.nextInt();
Now you will see that the prompts say "Enter number 0 :", which is probably not desirable. You can fix this by printing (counter + 1) when you are printing the prompt:
System.out.println("Enter number " + (counter + 1) + " :");
This is my first post.
Using a Scanner class, I'm trying to let user input to choose to repeat the program or quit. The thing is my Do loop statement repeats the program and does not exit even if the Do Loop is false and should exit the program.
// loop repeat or quit
do {
//initialize variable
int integer;
int x = 1;
int factorial = 1;
System.out.print("Please enter an integer \n");
integer = getInt.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = getString.next();
} while(quit != yes);
System.exit(0);
}
There were a few mistakes in your code, so I rewrote it a little bit and used the correct functions where you used incorrect ones.
public static void main(String args[])
{
// Scanner is used to take in inputs from user
Scanner scan = new Scanner (System.in);
String quit = "";
// loop repeat or quit
do {
//initialize variable
int integer = 0;
int x = 1;
int factorial = 1;
// User needs to enter integer, or it'll throw exception.
System.out.println("Please enter an integer");
integer = scan.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
// factorial = x!
while (x <= integer) {
factorial *= x;
x++;
};
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.println("do you want to quit? y or n");
quit = scan.next();
// if quit is NOT equal to y, we do it again
} while(!quit.equals("y"));
System.exit(0);
}
I hope the comments helps :)
I've edited your code and it now runs.
For future reference: include more comprehensive snippets so viewers of your code can more easily discover mistakes.
Problem: There is no way to guarantee the user only inputs y without any spaces . THe easy solution to this problem is to use the string method contains(). I've modified your loop so that if the user input y the program will exit and it now works. Let me know if this works and happy coding!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String quit ="";
do { //initialize variable
int integer; int x = 1; int factorial = 1;
System.out.print("Please enter an integer \n");
integer = in.nextInt();
//loop for factorial
//multiple each increment until it reaches the integer
while (x <= integer) {
factorial *= x;
x++;
}; // factorial=x*x
System.out.println("the factorial of the integer " + integer + " is " + factorial);
System.out.print("do you want to quit? y or n \n");
quit = in.next();
} while(!quit.contains("y"));
System.exit(0);
}
Shouldn't it be
while(quit != "y");
I also don't understand why you use System.out.print(); and then use \n when there's a perfectly good System.out.pritnln();
Also, since we're dealing with Strings the .nextLine(); is good enough for the Scanner. (You'll have to declare String quit as well.)
So my assignment is this
Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same.
I am having a hard time making it if the user only enters 1 number then both values will be set but at the same time making it loop as long as the user says yes.
public static void main(String[] args)
{
int maxNum = Integer.MAX_VALUE;
int minNum = Integer.MIN_VALUE;
String repeat;
String firstResponseString = JOptionPane.showInputDialog("Enter a Number ");
maxNum = Integer.parseInt(firstResponseString);
minNum = Integer.parseInt(firstResponseString);
String userRepeat = JOptionPane.showInputDialog(" Would you like to input another number? Y/N");
while(userRepeat.equalsIgnoreCase("Y"))
{
String num1String = JOptionPane.showInputDialog("Enter a Numer: ");
int num1 = Integer.parseInt(num1String);
if(num1 > maxNum)
{
maxNum = num1;
}
if(num1 < minNum)
{
minNum = num1;
}
userRepeat = JOptionPane.showInputDialog(" Would you like to input another number? Y/N");
}
JOptionPane.showMessageDialog(null, "Largest Number: " + maxNum + "\nSmallest Number: " + minNum, "Find Min and Max", JOptionPane.INFORMATION_MESSAGE);
}
I think I got it working now with this code
You may set the int minNum = Integer.MIN_VALUE and int maxNum = Ingerer.MAX_VALUE in declaration.
The String repeat serves no purpose since it's not used anywhere but in the declaration also the assignment of maxNum=... and minNum=.... is unnecessary since you're parsing the maxNum and minNum so they can be recognized by the JOptionpane.
Write a program that uses a while loop. In each iteration of the loop, prompt the user to enter a number – positive, negative, or zero. Keep a running total of the numbers the user enters and also keep a count of the number of entries the user makes. The program should stop whenever the user enters “q” to quit. When the user has finished, print the grand total and the number of entries the user typed.
I can get this program to work when I enter a number like 0, to terminate the loop. But I have no idea how to get it so that a string stops it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
int num;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
while (num != 0) {
if (num > 0){
sum += num;
}
if (num < 0){
sum += num;
}
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.nextInt();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Your strategy would be to get the input as a string, check to see if it is a "q", and if not convert to number and loop.
(Since this is your project, I am only offering strategy rather than code)
This is the rough strategy:
String line;
line = [use your input method to get a line]
while (!line.trim().equalsIgnoreCase("q")) {
int value = Integer.parseInt(line);
[do your work]
line = [use your input method to get a line]
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
int sum = 0;
String num;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
while (!num.equals("q")) {
sum += Integer.parseInt(num);
count++;
System.out.println("Enter an integer, enter q to quit.");
num = in.next();
}
System.out.println("You entered " + count + " terms, and the sum is " + sum + ".");
}
Cuts down on your code abit and is simple to understand and gives you exactly what you want.
could also add an if statement to check if they entered another random values(so program doesn't crash if the user didn't listen). Something like:
if(isLetter(num.charAt(0))
System.out.println("Not an int, try again");
Would put it right after the while loop, therefore it would already of checked if it was q.
java expects an integer but we should give the same exception. One way to solve this problem is entering a String, so that if the user first pressing is the Q, never enters the cycle, if not the Q. We assume that the user is an expert and will only enter numbers and the Q when you are finished. Within the while we convert the String to number with num.parseInt (String)
Integer num;
String input;
while(!input.equal(q)){
num=num.parseInt(input)
if(num<0)
sum+=1;
else
sumA+=1;
}
Im working on an assignment for an intro to java class and having some difficulty accounting for a situation when a user needs to give multiple inputs. The problem is given as follows:
"Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same."
My issue is that I cannot figure out how to make the program continuously ask the user if they want to input another number....for as many times as they say yes (obviously). I know I will have to use a loop or something, but I am a beginner with this and do not know where to start. Any help would be appreciated, and thanks in advance!
Here is what I have so far:
package findingminandmax;
import javax.swing.JOptionPane;
public class Findingminandmax
{
public static void main(String[] args)
{
String a = JOptionPane.showInputDialog("Input a number:");
int i = Integer.parseInt(a);
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
if ("yes".equals(b)) {
String c = JOptionPane.showInputDialog("Input another number:");
int j = Integer.parseInt(c);
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
} else {
JOptionPane.showMessageDialog(null, "The maximum number is " + i );
}
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
while(b.equalsIgnoreCase("yes")){
String c = JOptionPane.showInputDialog("Input another number:");
// your logic
b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
}
// then have your logic to print maximum and minimum number
But to get Yes/No inputs use a Confirm dialogbox rather than a input dialogbox
e.g.
int b = JOptionPane.showConfirmDialog(null, "Would you like to input another number? yes or no", "More Inputs", JOptionPane.YES_NO_OPTION);
while (b == JOptionPane.YES_OPTION) {
// your logic
}
while(true) {
//do stuff
if ("yes".equals(b)) {
//do other stuff
} else { break; }
}