How to collect input from user with dialog box? - java

Im working on an assignment for an intro to java class, and having a difficult time, 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."
I am having trouble getting the input dialog boxes to fit into my code and converting that input to integers that I can use for the calculations. Additionally I am not sure of how to account for the user entering more numbers than two, but Im not gonna go into that right now.
Any help would be appreciated, 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)
{
int i = 3;
int j = 2;
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}

For the input, use:
String s = JOptionPane.showInputDialog(message));
If you want to convert it to a integer:
int i = Integer.parseInt(s);
To a float:
float f = Float.parseFloat(s);
Or to a double:
double d = Double.parseDouble(s);
Also, in order to accept more than 1 input, you could use a for loop or a while:
int n = 5; // Number of times the input will be requested
for (int i = 0; i < n; i++) {
...
// Code here to accept the input
String s = JOptionPane.showInputDialog(message));
...
}
If you are going to store many inputs, you may want to store them in an array.
ArrayList

Related

Convert int to string in a loop

I want to ask how to convert an int value to string while runing in loop lets say i got an int value 1 at first running of loop then i got 2 and then 3 in the end i want a string with value "123"..
your answers would be very helpful.. THANKS
int sum = 57;
int b = 4;
String denada;
while(sum != 0)
{
int j = sum % b;
sum = sum / b
denada = (""+j);
}
how to convert an int value to string
String.valueOf function returns the string representation of an int value e.g. String x = String.valueOf(2) will store the "2" into x.
lets say i got an int value 1 at first running of loop then i got 2
and then 3 in the end i want a string with value "123"
Your approach is not correct. You need variables for:
Capturing the integer from the user e.g. n in the example given below.
Store the value of the appended result e.g. sum in the example given below.
Capturing the user's choice if he wants to continue e.g. reply in the example given below.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String reply = "Y";
String sum = "";
while (reply.toUpperCase().equals("Y")) {
System.out.print("Enter an integer: ");
int n = Integer.parseInt(scan.nextLine());
sum += n;
System.out.print("More numbers[Y/N]?: ");
reply = scan.nextLine();
}
System.out.println("Appnded numbers: " + sum);
}
}
A sample run
Enter an integer: 1
More numbers[Y/N]?: y
Enter an integer: 2
More numbers[Y/N]?: y
Enter an integer: 3
More numbers[Y/N]?: n
Appnded numbers: 123
The next thing you should try is to handle the exception which may be thrown when the user provides a non-integer input.

If number A is higher than number B, keep asking for lower user Input on number A

NB: Java beginner!
I am trying to make a program that asks the user to input two integers (Using JOption Pane dialog boxes). The program should then find the sum of all the numbers between the two input integers. For example if the user inputs 1 and 8, the program would show in System.out: 1+2+3+4+5+6+7+8=36. The first input dialog asks the user to enter a number, and the second to enter a higher number than the first. I want the program to check if number 2 actually is higher than number 1, and if not, tell the user that number 2 should be higher and prompt for a new entry.
I am currently unable to check if number 2 is higher than number 1
I have tried using different if statement and a while loop. I manage to get the program to show a message dialog if the second number is higher than the first, and ask the user for a new input. However I am unable to get the new input from the user, check if it is correct, and if it is continue with the calculations.
package numbersum;
public class NumberSum {
public static void main(String[] args) {
String input1 = JOptionPane.showInputDialog( "Write a number :" );
String input2 = JOptionPane.showInputDialog( "Write a larger number :" );
int number1 = Integer.parseInt(input1);
int number2 = Integer.parseInt(input2);
if ( number2 <= number1 ) {
JOptionPane.showMessageDialog(null,"The second number must be higher
than the first");
}
int sum=0;
for ( int i = number1; i <= number2; i++ ) {
sum = sum + i;
System.out.print( i + "+" );
}
System.out.print( "=" + sum );
}
You need to use a while loop and provide the JOptionPane untill the user enters valid numbers. Also be sure to test what happens with your application if the user inserts a non numeric value, it probably will crash at the moment :)
public static void main(String[] args) {
// initially set the number 2 smaller than number 1
int number2 = 0;
int number1 = 1;
while (number2 < number1) {
String input1 = JOptionPane.showInputDialog("Write a number :");
String input2 = JOptionPane.showInputDialog("Write a larger number :");
number1 = Integer.parseInt(input1);
number2 = Integer.parseInt(input2);
if (number2 < number1)
JOptionPane.showMessageDialog(null, "The second number must be higher!");
}
int sum = 0;
for (int i = number1; i <= number2; i++) {
sum = sum + i;
System.out.print(i + "+");
}
System.out.print("=" + sum);
}

Product of Number input by user, program stops when user inputs 0

i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

Checking for negative values with scanner in

I have just written my first java program for a class I am taking which is used to give a student graduation information based on the credits for each class remaining. I have gotten everything to work except the required entry to check for negative values. Please see below and let me know if you have any ideas. Thanks in advance.
package txp1;
import java.util.ArrayList;
import java.util.Scanner;
public class txp1 {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the University Graduation Calculator!");
System.out.println();
System.out.println("This calculator will help determine how many terms "
+ "you have remaining and your tuition total based upon credits"
+ " completed per semester.");
System.out.println();
double tuitionpersem = 2890;
System.out.println("We will begin by entering the number of credits for"
+ " each class remaining toward your degree.");
double sum = 0;
ArrayList<Double> credit = new ArrayList<>();
{
System.out.println("Please enter the number of credits for each individual class on a separate line and then press enter, Q to quit:");
Scanner in = new Scanner(System.in);
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
while (in.hasNextDouble()) {
credit.add(in.nextDouble());
}
for (int i = 0; i < credit.size(); i++) {
sum += credit.get(i);
}
System.out.println("Total credits remaining: " + sum);
}
int perterm = 0;
System.out.println("How many credits do you plan to take per term? ");
Scanner in = new Scanner(System.in);
perterm = Integer.parseInt(in.nextLine());
if (perterm <= 0);
{
System.out.println("The number of credits must be greater than zero!");
}
double totterms = sum / perterm;
totterms = Math.ceil(totterms);
System.out.print("Your remaining terms: ");
System.out.println(totterms);
double terms = (totterms);
System.out.print("The number of months to complete at this rate is: ");
System.out.println(6 * terms);
double cost = terms * 2890;
System.out.println("The cost to complete at this rate is: " + cost);
}
}
double number = 0;
number = Integer.parseInt(in.nextLine());
if (number <= 0);
The ";" at the end of if statement is the end of it. You are not doing anything with the result of number <=0. I believe you meant it to be like:
if (number <= 0){
//operations….
}
Notice that you create number of type double, then assign an int (parsed from String) to it. You can use nextDouble method to get a double directly, and if you plan this number to be an Integer anyway then use type int instead of double and nextInt instead of parsing. For more information about parsing from input, check Scanner documentation.
Your if statements terminate if you put a semi colon at the end of them. Effectively ending your logic right there. The program basically checks the condition and then moves on. Which in turn executes your second statement regardless of what number <= 0 resolves to.
//Does not get expected results
if (number <= 0);
{
//Gets executed regardless of condition
System.out.println("The number of credits must be greater than zero!");
}
//Gets expected results
if (number <= 0)
{
//Gets executed only if the condition returns true
System.out.println("The number of credits must be greater than zero!");
}
Edit: Changed due to some helpful input.
2nd Edit: I would also consider putting a loop in your code that makes the user re-enter input to get the desired value. If you put in a negative value your code will just spit the error message and keep running which can make you scratch your head. Unless your teacher isn't grading on that then forget all of what I just said. =p

Categories

Resources