Input to assign value to double variable - java

I'm trying to get it where the user inputs a 1 or 2 for a predetermined values. Then using that to calculate a final cost.
Example:
Would you like the red or orange box? 1 for red, 2 for orange
The red would cost $10 and the orange $12.
How do I connect the inputs 1 and 2 to $10 and $12? Do I use switch or if?

Both options work. I personally prefer using the switch statement as it makes the code a bit more readable.
import java.util.Scanner;
public class Untitled {
public static void main (String[]args) {
Scanner s = new Scanner(System.in);
// this is where you store your items - you would obviously have to create the class and its methods first
// ArrayList <Item> items = new ArrayList<>;
// items.Add(new Item(SomePrice, SomeName);
System.out.println("Item 1 or 2");
String input = s.nextLine();
// Option 1
switch(input) {
case ("1"): {
System.out.println("Cost is 1");
// some method to retreive an item from the list of Items carrying the name one
// get user Input
// update the item in the list
break;
}
case ("2"):{
System.out.println("Cost is 2");
break;
}
}
// Option 2
if (input.equalsIgnoreCase("1"))
System.out.println("Cost is 1");
else if (input.equalsIgnoreCase("2"))
System.out.println("Cost is 2");
}
}

Related

How can i add the static variable number in a method?

I create a ProductMenu class to perform the add, search, delete and update product tasks and it only use the array. What problem that i face is how to add static variable in a method because i failed to add the maximum number of array after add a product into array. Hope can help and thank you.
public static void addProduct(){
Product product = new Product();
System.out.println("================================");
System.out.println(" Add Product ");
System.out.println("================================");
System.out.println("Product ID :- " + Product.getProdId());
System.out.print("Enter product name: ");
String prodName = input.next();
System.out.print("Enter product price: ");
double prodPrice = input.nextDouble();
product.setProductId(Product.getProdId());
product.setProductName(prodName);
product.setProductPrice((double)prodPrice);
products[productIndex] = product;
numOfArray++; // should be add ?
productIndex++; // should be add also?
ProductMenu.main(null); //back to main
}
My class
public class ProductMenu {
static Scanner input = new Scanner(System.in);
static int productIndex; //should be add after addProduct()
static int numOfArray = 1; //should be add after addProduct()
static Product[] products = new Product[numOfArray];
public static void main(String[] args) {
int menuOption;
do{
menu();
System.out.print("Enter your choice: ");
menuOption = input.nextInt();
switch(menuOption){
case 1:
addProduct();
break;
case 2:
System.out.print("halo" + products[0].toString());
break;
case 3:
break;
case 4:
break;
default:
System.out.print("Invalid option. Please try
again.\n");
break;
}
}while(menuOption!=1 && menuOption!=2 && menuOption!=3 &&
menuOption!=4 );
}
public static void menu(){
System.out.println("================================");
System.out.println(" Product Menu ");
System.out.println("================================");
System.out.println("1. Insert Product\n2. Update Product\n3.
Search Product\n4. Delete Product\n");
}
This is error msg that mean array number already more than limit and why i ask if i not wrong.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ProductMenu.addProduct(ProductMenu.java:64)
at ProductMenu.main(ProductMenu.java:21)
at ProductMenu.addProduct(ProductMenu.java:68)
at ProductMenu.main(ProductMenu.java:21)
I was wondering whether you could replace array with arraylist in your code. Arraylists are backed by arrays in background and you need not worry about arrayindexoutofbound exception while handling the data
To your problem: I would use an ArrayList or a LinkedList because it has a dynamic size. The size of an array cannot be changed after initialization and yours is set to 1. That will cause problems.
Addition: You do not need to call ProductMenu.main(null); //back to main because your addProduct function is called in the main method and after executing your function your program will continue in the main function.
As you need to use Array only then create one function add() which will first check size of array, if there is space left then add element else create new array of double size , copy all previous elements and add new one at end.
Also as size is static variable you don't have to pass to your method. Your method is also static and both method and variable in same class so you can directly use variable in method.

Is there a way to make a user list?

For my coding class I have to build a shopping list by having the user enter the number of items they need and then each item (one at a time). I then have to output the final shopping list in a multi-line dialogue box (one item per line). I have the first two parts done where users enter the number of items and what items they would like, but can't figure out how to output all the items. Any help would be great, thanks! Also, I am using jgrasp and we don't use println to output messages.
I've tried Output.showMessage("Shopping list \n" + items); and
Output.showMessage(items.toString());
public class ShoppingList
{
public static void main (String [] args)
{
String items;
int numItems, count;
numItems = Input.readInt("Enter number of items: ");
count = 0;
while (count < numItems)
{
items = Input.readString("Enter item: ");
count = count + 1;
}//end while
Output.showMessage(items.toString());
} //end main
} //end ShoppingList
The output should show a list of user entered items like:
Shopping List:
Bananas
Milk
Items cannot be of string type because whenever the line
items = Input.readString("Enter item: ");
is executed, the previous value of items is overwritten.
If you are allowed to for your homework, it's ideal to make items an array otherwise you would have to change the previous statement to
items += Input.readString("Enter item: ");
items += '\n';
Note:items here is one long String.

I am having issues with a basic contact manager that I am creating.

I am having some problems with this bit of code. The first thing I did was obviously created some Arrays, these arrays would hold all the information for each contact, as I am building a basic contact manager. My main method just calls my menu method to start the sequence. At my menu, the user has a choice of what they want to do. Whichever choice they choose will be determined by the number they enter on their keyboard. Which in turn, will activate a different method.
The problems I am having is as follows:
After pressing "1" which is to view all contacts, the computer either spits out 100 nulls or 100 repeats of whatever I last inputted in the "2", add contacts.
Although yes I do want my menu to repeat itself after an action has taken place, it does it too instantaneously. For example, as soon as all the repeats happen after I push "1" it goes straight back to the main menu, and it is difficult to read everything this way.
import java.io.IOException;
import java.util.Scanner;
``public class MainHub {
// global variables that will be needed
static String[] name = new String[100];
static String[] number = new String[100];
static String[] email = new String[100];
static String[] address = new String[100];
static String[] birthday = new String[100];
static String[] nickname = new String[100];
static int x;
public static int counter = 0;
static Scanner in = new Scanner(System.in);
public static void main (String[] args) throws IOException{
menu(); // call menu method to start program
}
//Holds all the information for the menu
public static void menu() throws IOException{
int choice = -1; //start at -1 as to not compete with an index number
while (choice != 7){ //while loop to get a choice from user
//telling the user what everything is, simple output message
System.out.println("\t Main Menu\n");
System.out.println("Enter the corrosponding number for what you want to do.\n");
System.out.println("1.View all contacts\n2.Add contact\n3.Edit contact\n4.Delete contact\n5.Save contact list\n6.Load contact list\n7.Exit");
choice = Integer.valueOf(in.nextLine()).intValue(); //this allows the user input to be read and used to make a choice
switch(choice){
case 1: viewAllContacts(); //if user inputs 1, call method to view all the contacts
break; //stop the loop
case 2: addContact(); //if user inputs 2, call method to add a contact
break; //stop the loop
case 3: editContact(); // if user inputs 3, call method to view contacts and choose one to edit
break; //stop the loop
case 4: deleteContact(); // if user inputs 4, call method to view contacts and choose one to delete
break; //stop the loop
case 5: saveContact(); // if user inputs 5, call method to save current contact list into a text file
break; //stop the loop
case 6: loadContact(); // if user inputs 6, call method to load a text file to input contacts into array
break; //stop the loop
case 7: System.out.println("You are exiting"); // if user inputs 7, tell user he is leaving
break; //stops the loop
default: System.out.println("That is not one of the options."); // if user doesn't input one of above numbers, it will tell user not an option
}
}
}
//holds information, once called upon the user will be able to see all their contacts
public static void viewAllContacts(){
while(counter<100){ //while the counter has less than 101 it will print out the full list of contacts
if(counter>0){ //if counter is greater than 0 print list of contacts
System.out.println("Full name: " +name[x]);
System.out.println("Number: " +number[x]);
System.out.println("E-mail Address: " +email[x]);
System.out.println("Home Address: " +address[x]);
System.out.println("Birthday: " +birthday[x]);
System.out.println("Nickname: " +nickname[x]);
System.out.println(" "); //space so that way the contact list is a bit prettier
counter++;
}else{
System.out.println("There are no contacts in your list yet."); //else tell user there is no contacts
}
}
}
//lets the user add a contact and all the information
public static void addContact() throws IOException{
//as long as the counter is less than 101 you can add contacts
if(counter<100){
System.out.println("Enter Contact's Full Name: "); //allows user to add a name to contact
name[x] = in.nextLine(); //whatever is typed will be added into name variable
System.out.println("Enter Contact's Number: "); //allows user to add a number to contact
number[x] = in.nextLine(); //whatever is typed will be added into number variable
System.out.println("Enter Contact's E-mail Address: "); //allows user to add an E-mail address to contact
email[x] = in.nextLine(); //whatever is typed will be added into email variable
System.out.println("Enter Contact's Home Address: "); //allows user to add a home address to contact
address[x] = in.nextLine(); //whatever is typed will be added into address variable
System.out.println("Enter Contact's Birthday: "); //allows user to add a birthday to contact
birthday[x] = in.nextLine(); //whatever is typed will be added into birthday variable
System.out.println("Enter Contact's Nickname: "); //allows user to add a nickname to contact
nickname[x] = in.nextLine(); //whatever is typed will be added into nickname variable
counter++; //adds 1 to counter to allow space for next contact in arrays
}else{
System.out.println("Sorry, the contact list is full."); //if counter is 101 it will print the contact list is full
}
System.out.println("Your contact has been added");
}
The problem is that you are using x as the index of the array, but x is never being incremented.
As you are incrementing counter
try
System.out.println("Full name: " +name[counter]);
likewise with your adding a contact
Sort out your indexes.

How To Store Multiple Words As An ArrayList Value

public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
String newItem = inputread.next();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
This is my code, I'm just learning Java and trying to made a little "To-Do List" type program. As it stands, I can only add one word at a time. If, for example, I type "Pick Up Milk", the arrayList only stores "Pick".
I tried using inputread.nextLine() above, but then I get an "InputMismatchException". Any advice? I'm sure it's something simple.
Edited to include the whole class, per request:
public class ToDo {
Scanner inputread = new Scanner(System.in);
ArrayList<String> toDoList = new ArrayList<String>();
public void menu() {
clearConsole();
System.out.println("Welcome to the To-Do program.");
System.out.println();
System.out.println();
System.out.println("Please select an option from the following menu, using the number.:");
System.out.println("1- View To-Do List");
System.out.println("2- Add Item To List");
System.out.println("3- Remove Item From List");
int userinput = inputread.nextInt();
switch (userinput) {
case 1:
clearConsole();
displayList();
System.out.println();
System.out.println("This is your list. Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
break;
case 2:
clearConsole();
addItem();
break;
case 3:
clearConsole();
deleteItem();
break;
}
}
public void clearConsole() {
for (int i = 0; i < 25; i++) {
System.out.println();
}
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
String newItem = inputread.nextLine();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
public void displayList() {
if (toDoList.isEmpty()) {
System.out.println("For [REDACTED]'s sake, add an activity.");
} else {
for (String listItem: toDoList) {
System.out.println(listItem);
}
}
}
public void deleteItem() {
System.out.println("Please choose the number of the line you want to delete:");
displayList();
int userinput = inputread.nextInt();
int listPos = userinput - 1;
toDoList.remove(listPos);
System.out.println("That item has been deleted. Type any key and press Enter to continue.");
String discardMe = inputread.next();
menu();
}
}
I would suggest using a BufferedReader instead of the Scanner class. The problem with a Scanner is that it looks for tokens between white spaces and new lines, so when you add something like Go to the store, each token between the white spaces will get picked up, and you will end up with go to the store, rather than 1 large token. You can get input using the BufferedReader by declaring it using:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
Then, in your addItem() method, in a while(true) loop, you read the input from the reader, then check if it is empty or not. IF it is empty, then you break the loop and exit the function, otherwise add an item to your list.
System.out.println("Please type the item to add to the To-Do List"); // Output
while (true) { // Continue adding items until user just hits enter
String newItem = buf.readLine(); // read user input
if (newItem == null || newItem.isEmpty()) { // check if the user entered anything, or just hit enter
break; // If they didn't enter anything, then break the loop and drop out of the function
}
toDoList.add(newItem); // if they did enter something, add it to your to-do list
}
For example, to test this I used a main method:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
List<String> toDoList = new ArrayList<String>();
System.out.println("Please type the item to add to the To-Do List");
while (true) {
String newItem = buf.readLine();
if (newItem == null || newItem.isEmpty()) {
break;
}
toDoList.add(newItem);
}
System.out.println("Your item has been added! Type any key and press Enter to continue");
for (String s : toDoList) {
System.out.println(s);
}
}
Then, when prompted for input I entered:
Please type the item to add to the To-Do List
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife
And for output I got:
Your item has been added! Type any key and press Enter to continue
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife
You have several problems in this code.
Let's first address your input issues.
In the menu, you read a number. When you use scanner.next(), scanner.nextInt() etc., it reads the following item up to - but not including - any white space or newline. So the white space or newline remain in the buffer waiting to be read.
Now, when you go to the addItem() and use nextLine(), it reads just that whitespace or newline. If it was just a newline (a Return you pressed), then you get an empty string, and you probably don't want to add that to the list. If you use next() it will skip that newline but... it will read just one word.
So you need to have a nextLine() after your nextInt() in the menu. After you read your integer, you'll clear the buffer up to and including the newline.
Then, inside the addItem() method, you'll be able to use nextLine() again, because it will now start on a fresh new line - and it will read the next line in its entirety.
Also, the discardMe part has to be with nextLine(), not with next(), otherwise it will not clear the end-of-line for the next operation.
Your other problem is something you didn't ask about. What you currently do is basically go into the menu, then go into an operation, then go into the menu, then an operation. You keep calling more and more functions, and you never return, or rather, you return from all when you display the list.
In time, this may cause a stack overflow.
The proper way to do this is not to call menu() from inside the operational methods, but rather, to have a loop in the menu() method, which shows the menu, calls the appropriate operational method, and when it returns (clears its space on the stack), loops back to the menu and so on. This keeps your stack nice and flat.
And of course, you should have a "Quit" option on your menu.
an example for Stultuskes idea:
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
try (Scanner in = new Scanner(System.in)) {
while (in.hasNext()) {
String newItem = in.next();
toDoList.add(newItem);
System.out
.println("Your item has been added! Type any key and press Enter to continue");
}
}
System.out.println(toDoList);
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
//The skip gets over the leftover newline character
inputread.skip("\n");
String newItem = inputread.nextLine();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
Putting in the skip fixed it for me. I want to thank you guys for your answers.

Java: variable not initialized

i am getting a "variable selection may not have been initialized in displayMenu(selection). and im not sure why. is it not initialized in the displayMenu model or am i missing something? does "selection = keyboard.nextInt" not count as an initialization? im kind of confused at why i am getting this error. here is the code:
import java.util.Scanner;
import java.io.*;
public class LanguageTranslatorIB
{
public static void main(String[] args)
{
// local variable to hold the menu selection
int selection;
do
{
// display the menu
displayMenu(selection);
// perform the selected operation
switch (selection)
{
case 1:
System.out.println("Good Morning.");
case 2:
System.out.println("Buongiorno.");
case 3:
System.out.println("Buenos dias.");
case 4:
System.out.println("Guten morgen.");
case 5:
System.out.println("GoodBye!");
}
}
while (selection != 5);
}
// the displayMenu module displays the menu and gets and validates
// the users selection.
public static void displayMenu(int selection)
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}
When you pass the variable selection into displayMenu the original variable does not change. The variable that is changed inside that method is a copy. Anything you do inside that method has absolutely no effect on the original selection
Therefore selection has not been initialized as is correctly pointed out by the compiler
You need to redesign the displayMenu to return a value which will be assigned to selection. No input to that method is needed
On another note, you probably want to add break after each System.out.println inside the case statements. If you don't the control will fall through to each next case.
Change displayMenu not take a parameter but rather to return the selected int. Assign that to selection:
selection = displayMenu();
and...
public static int displayMenu()
{
int selection = 0;
Scanner keyboard = new Scanner(System.in);
// ....
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
//...
}
return selection;
}
Your primitive variables are passed to methods as copy, not reference. So when you're calling
displayMenu(selection);
this method is only working with the copy within the method, not the variable out of it itself.
in Java local/block variables need to be explicitly initialized at declaration. un-initialized local variables give this error. Ifyou assume that the selection local variable will be given the default value that an int has in Java then you are wrong. The same is not the case with class level variables, the ones which you define in your class as properties. These variables are assigned their default values automatically by compiler.
Since you havent assigned any value to 'selection' before using in later on so you get this error.
In your main method, selection does not store any value at any point. You need to setup displayMenu to return an integer to selection
When you call displayMenu(selection); java passes the value of the selection variable to the displayMenu() method. The variable hasnt been initialized yet.
Then you're trying to set the value of selection variable inside the displayMenu() method.
However, the selection variable that you have as a parameter of the displayMenu() is local to that method and even though the value of the local selection variable is set, the selection variable inside the main method still remains uninitialized.
To tackle this : Create an instance variable.
public class LanguageTranslatorIB
{
int selection;
public static void main(String[] args)
{
displayMenu();
//Rest of the code follows;
}
}
public static void displayMenu()
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}

Categories

Resources