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; }
}
Related
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.
Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but Iād also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!
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;
}
import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.