storing "inputdialog" data in an array - java

I have written a Java menu console which asks users to select an option. I have successfully compiled the menu system which takes a users input and directs them to a menu page. The first of these pages asks 2 questions using "InputDialog" boxes.
Here is the code for the "InputDialog", when I run the java console i can access and enter information into these boxes fine.
private void enterInfor()
{
String carInfo;
int carHours;
int i = 0;
double fee = Double.parseDouble("7.50");
double sum = 0;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car 1 entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carHours == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
I have the "String" and "int" information to store the information that is input by the user, however I need the program to store at least 20 different inputs which can be accessed later in the console.
I have successfully made a console repeat information and then output the combined answers using a for loop =
"for(int Num=1; Num <= 6; Num++)"
and this allowed me to repeat a set of questions and then compile the information into statistics afterwards but for this console I need the "InputDialog" to only take in one set of answers at a time and then return the user to the initial console menu.
I'm sorry again if this is all pretty vague of information or formats, just need some kind of help on how/where to put the correct code.

Related

Java and Arrays

I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.

Asking the user to think of, and write down, a number between 1 and 1,000,000 in java

Hi guys so I'm working on writing a program that's asking a user to think of and write down a number between 1 and 1,000,000.
then it asks questions like "Is it greater than 500000?", and the user answers "Yes" or "yes" or "no or "NO", or "Got It!" now this where I'm stuck at. I don't know how to get it to ask that questions
this is the code i got so far :
import javax.swing.JOptionPane;
public class Questions {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, Questions");
String S = JOptionPane.showInputDialog("Enter a number between 1 and 1,000,000");
int i = 1000000;
if (i>500000){
}
}
how do i use JOptionPane.showInputDialog to ask questions and get answers ?
Any help is appreciated.
First of all, I strongly recommend debugging in the console until your logic is complete, then work on the GUI.
You are basically trying to implement a binary search, where the computer should get the answer right in log(N) guesses.
Here is some code to get you started. The GUI should be fairly straightforward. Read the appropriate Javadocs.
try (Scanner k = new Scanner(System.in);) {
String input;
int lo = 0;
int hi = 1000000;
int mid;
while (true) {
mid = (lo + hi) / 2;
System.out.printf("Is it equal to %d?\n", mid);
if (!input.equalsIgnoreCase("Got it!")) {
break;
} else {
System.out.printf("Is it greater than %d?\n", mid);
input = k.nextLine();
if (input.equalsIgnoreCase("yes")) {
lo = mid;
} else {
hi = mid;
}
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
You can use showConfirmDialog() to ask a yes or no question...Here is an example you would need to change the values as these are hard coded but you should be able to figure out how to put this in a loop and change values dynamically based upon user entry:
int answer = JOptionPane.showConfirmDialog(null, "Is 500,000 your number?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(answer == 1)
{
answer = JOptionPane.showConfirmDialog(null, "Is 500,000 less than your number?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
}
This way the user doesn't have to type "yes" or "no" or "got it" which will eliminate human error...
Yes - will return 0
No - will return 1
The second question will tell u whether there number is lower or higher than the proposed number depending on whether they answer yes or no...
First you should change S to an integer because you're asking the user to enter an integer. Second, assuming the program is supposed to try to guess the number, you would start with 500,000 and keep guessing in halves until you get the entered number (it looks like you got this part). So here is an outline (I'm not quite sure what the exact syntax is for JOptipnPane but you can find commands for input and output):
String YesOrNo = JOptionPane.ShowInputDialog ("is the number higher than 500,000? ")
If YesOrNo.equalsIgnoreCase ("yes") then guess 750,00 next if no guess 250,000 next
This is an outline see if you can get the rest if not comment for further help
First you should change S to int because you are asking the user to enter an integer. Second, assuming the program is supposed to try to guess the number, you would start with 500,000 and keep guessing in halves until you get the entered number (it looks like you got this part). So here is an outline (I am not quite sure what the exact syntax is for JOptipnPane is but you can find commands for input and output):
String yesOrNo = JOptionPane.ShowInputDialog("is the number higher than 500,000? ")
If yesOrNo.equalsIgnoreCase("yes") then guess 750,00 next if no guess 250,000 next
This is an outline see if you can get the rest. If not comment for further help.

Java: Saving User Input to be Calculated in a Loop

Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);

Program not displaying everything it's supposed to

I am writing an inventory program for a book store that is comprised of two classes and multiple methods within these classes.
The method I'm having the most trouble with is my purchase() method which is supposed to interactively process a purchase, update the array after the purchase, and display totals for items sold and total amount of money made that day.
The method is supposed to follow these 10 steps:
Ask the user to enter the ISBN number of the book they'd like to purchase.
Search the array for the object that contains that ISBN.
If the ISBN isn't found in the array, display a message stating that we don't have that book.
If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock.
If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase.
If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity.
When they enter a 0 for the ISBN, the Scanner is supposed to close
Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased.
Print the updated array.
Display a count of how many books were purchased, and how much money was made from the purchase.
But as my code is written, after the Program prompts me to enter an ISBN, nothing happens, it just continually lets me enter numbers with no additional output.
Here is the code I have for this method. I'm pretty sure it's probably an issue with my loop as I'm not very good with looping. Can anyone spot what I'm doing wrong?
public static Book[] purchase(Book[] books) {
int itemsSold = 0;
double totalMade = 0;
double price;
int copies;
String isbn;
Scanner input = new Scanner(System.in);
int desiredCopies = 0;
int index;
double total = 0;
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
String desiredIsbn = input.next();
for (index = 0; index < books.length; index++) {
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() > 0) {
System.out.println("How many copies of this book would you like to purchase?");
if (!books[index].getISBN().equals(desiredIsbn))
System.out.println("We do not have that book in our inventory.");
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() == 0)
System.out.println("That book is currently out of stock.");
desiredCopies = input.nextInt();
}
if (desiredCopies > books[index].getCopies())
System.out.println("We only have " + books[index].getCopies() + "in stock. Please select another quantity: ");
desiredCopies = input.nextInt();
books[index].setCopies(books[index].getCopies() - desiredCopies);
if (input.next().equals(0))
System.out.println("Thank you for your purchase, your order total is: $" + total);
input.close();
total = books[index].getPrice() * desiredCopies;
itemsSold += desiredCopies;
totalMade += total;
System.out.print(books[index]);
System.out.println("We sold " + itemsSold + " today.");
System.out.println("We made $" + totalMade + "today.");
}
return books;
}
Any help would be greatly appreciated.
You are not matching every possible condition
Your if statements aren't covering all the possible permutations of conditions apparently.
You should use always use an if/else if/else block to make sure you cover all your conditions. Outside this there is absolutely no way for anyone to provide any actual solution with so little to go on.
Also
Scanner and StringTokenizer are two of the worst designed classes in the JDK outside Date and Calendar. They cause endless trouble for new people and are avoided by the veterans.

Java Error When attempting to use the return from a method as an item in an if statement

I keep getting the following errors:
Cannot find symbol
Variable find
cannot find symbol
method getdata(int)
I am sure I am making this way more difficult than it is, but I am not sure how make this work so that the return from searching through the array, can be seen and evaluated by the if statement.
//assigns manager identification
manID = keyboard.nextInt();
//Fibonacci binary array for passwords
int[] passWArray = {00000000,00000001,00000001,00000010,00000011,00000101,00001000,00001101};
//item = find.getdata(manID);
if (getdata(manID) != -1)
{
//Do work here
dblPayRate = 10.85;
dblGrossPay = (intHours * dblPayRate) + (15.00);
dblTaxes = dblGrossPay * 0.19;
dblGrossPay -= dblTaxes;
//Print information to user
System.out.print("\n\n$" + df2.format(dblTaxes) +
" was withheld from this paycheck in taxes after working "+ intHours + " hours.\n\n");
System.out.print("The amount \"Employer Here\" owes you is $" + df2.format(dblGrossPay) + "\n");
}
else
{
// Dialog box for incorrect password
JOptionPane.showMessageDialog(null, "Invalid Entry! Contact the BOFH!");
//exits program (Note: needed for any JOptionPane programs)
System.exit(0);
}
}// end of long if statement for >50 hours
}//end of main method
public int find(int[] passWArray, int manID)
{
//search for manID in passWArray array
for (int index = 0; index < passWArray.length; index++)
if ( passWArray[index] == manID )
return manID;
//-1 indicates the value was not found
return -1;
}// end of find method
Change
if (getdata(manID) != -1)
into
if (find(passWArray , manID) != -1)
BTW those numbers don't magically become binary because they only contain 0's and 1's. Here's a hint:
int thirteen = Integer.parseInt("00001101", 2)
EDIT: in response to your next error
For now make the method static:
public static int find(int[] passWArray, int manID)
Eventually you might want to think about your 'Object-Oriented design' and just use the main() method as an entry point. Within main you create an instance of a class and let it do its work. In this way you can use the powers of O-O like encapsulation and inheritance and don't have to make everything static.
EDIT2: Afterthought
Your program seems to have the following 'actions':
user interaction
authentication
calculation
And there seem to be the following 'things' in your domain:
user
password
keyboard
display (command line and screen)
calculation
A good rule of thumb for an O-O design is to convert some of the 'things' and 'actions' already present in your domain into classes. A good class has a single responsibility and shares as little as possible of its data and methods with other classes (this is called information hiding).
Here's a class diagram that comes to mind:
User (represents a user, contains a single field 'password')
Authenticator (authenticates a user, contains the list of allowed passwords)
Console (all user interaction, either use System.out/in or Swing, but don't mix them)
Calculator (it calculates shit)

Categories

Resources