import java.util.ArrayList; import java.util.Scanner; public class ShoppingCartManager{ //Printmenu method to print the following menu of options to manipulate the shopping cart. public static void printMenu() { // System.out.println(); System.out.println("MENU"); System.out.println("a - Add item to cart"); System.out.println("d - Remove item from cart"); System.out.println("c - Change item quantity"); System.out.println("i - Output items' descriptions"); System.out.println("o - Output shopping cart"); System.out.println("q - Quit"); }//End of printMenu //executeMenu method that takes 3 parameters: a character representing the user's choice, a shopping cart, and a Scanner object. public static void executeMenu(char userOption, ShoppingCart shopCart, Scanner scnr) { //Initializing variables used in this method String itemName, itemDescription; int itemPrice, itemQuantity; ItemToPurchase item; String tempNewLine; //scnr.nextLine(); //New line before beginning the filter tempNewLine = scnr.nextLine(); //Use of switch to filter the commands as per the user input switch (userOption) { case 'a': System.out.println("ADD ITEM TO CART"); System.out.println("Enter the item name:"); itemName = scnr.nextLine(); System.out.println("Enter the item description:"); itemDescription = scnr.nextLine(); System.out.println("Enter the item price:"); itemPrice = scnr.nextInt(); System.out.println("Enter the item quantity:"); itemQuantity = scnr.nextInt(); //String itemN, int itemP, int itemQ, String itemDesc item = new ItemToPurchase(itemName, itemDescription, itemPrice, itemQuantity); shopCart.addItem(item); break; //End of case 'a' case 'd': System.out.println("REMOVE ITEM FROM CART"); System.out.println("Enter name of item to remove:"); itemName = scnr.nextLine(); shopCart.removeItem(itemName); break; //End of case 'd' case 'c': System.out.println("CHANGE ITEM QUANTITY"); System.out.println("Enter the item name:"); itemName = scnr.nextLine(); System.out.println("Enter the new quantity:"); itemQuantity = scnr.nextInt(); item = new ItemToPurchase(); item.setName(itemName); item.setQuantity(itemQuantity); shopCart.modifyItem(item); break; //End of case 'c' case 'i': System.out.println("OUTPUT ITEMS' DESCRIPTIONS"); shopCart.printDescriptions(); break; //End of case 'i' case 'o': System.out.println("OUTPUT SHOPPING CART"); shopCart.printTotal(); break; //End of case 'o' }//End of case }//End of executeMenu //main public static void main(String [] args) { Scanner scnr = new Scanner(System.in); String customerName, currentDate; //Initializing customer Name and current date char userOption; //Prompt user for input System.out.println("Enter Customer's Name:"); customerName = scnr.nextLine(); System.out.println("Enter Today's Date:"); currentDate = scnr.nextLine(); System.out.println(""); // ShoppingCart shopCart = new ShoppingCart(customerName, currentDate); //Output the user input // System.out.println("Customer Name: " + shopCart.getCustomerName()); // System.out.println("Today's Date: " + shopCart.getDate()); System.out.println("Customer Name: " + customerName); System.out.println("Today's Date: " + currentDate); System.out.println(""); //Object of shopping cart ShoppingCart shopCart = new ShoppingCart(customerName, currentDate); // //prompt for the user's choice of menu options // printMenu(); // System.out.println(); // System.out.println("Choose an option:"); //Menuoptions filter while (true) { printMenu(); System.out.println(); System.out.println("Choose an option:"); userOption = scnr.next().charAt(0); //Using while to loop the Choose an option in case user inputs wrong input multiple times while ((userOption != 'a') && (userOption != 'd') && (userOption != 'c') && (userOption != 'i') && (userOption != 'o') && (userOption != 'q')) { System.out.println("Choose an option:"); userOption = scnr.next().charAt(0); } //End of inner while if (userOption == 'q'){ break; //quit upon pressing 'q' } //End of inner if executeMenu(userOption, shopCart, scnr); //prompt for the user's choice of menu options System.out.println(); // printMenu(); // System.out.println(); // System.out.println("Choose an option:"); } //End of while } //End of main } //End of class public class ShoppingCart{ private String customerName; private String currentDate; private ArrayList<ItemToPurchase> cartItems; //Default Constructor public ShoppingCart(){ customerName = "none"; //Initialized in default constructor to "none" currentDate = "January 1, 2016"; //Initialized in default constructor to "none" cartItems = new ArrayList<>(); } //End of Default Constructor //Parameterized Constructor public ShoppingCart(String customerN,String date){ customerName = customerN; currentDate = date; cartItems = new ArrayList<>(); } // End of Parameterized Constructor //Mutators public void setCustomerName(String customerN){ customerName = customerN; } public void setDate(String date){ currentDate = date; } //Mutators End //Gettors public String getCustomerName(){ return customerName; } public String getDate(){ return currentDate; } //Gettors End //public member Methods //addItem(). Adds an item to cartItems array. Has a parameter of type ItemToPurchase. Does not return anything. public void addItem(ItemToPurchase item) { cartItems.add(item); } //End addItem //removeItem(). Removes item from cartItems array. Has a string (an item's name) parameter. Does not return anything. public void removeItem(String itemName) { // int i = 0; // boolean found = false; // // Search for items in ArrayList // while ( (!found) && (i < cartItems.size()) ) { // if (cartItems.get(i).equals(itemName)) { // cartItems.remove(i); // Remove // found = true; // } //End of if // ++i; // } //End of While // if (!found) // { // System.out.println("Item not found in cart. Nothing removed."); // } //End of if boolean found = false; for (int i = 0; i < cartItems.size(); i++){ if (cartItems.get(i).getName().equals(itemName)) { // pos = i; found = true; cartItems.remove(i); break; } } if (!found) { System.out.println("Item not found in cart. Nothing removed."); } } //End of removeItem //modifyItem(). Removes item from cartItems array. Has a string (an item's name) parameter. Does not return anything. public void modifyItem(ItemToPurchase item) { int i = 0, pos; boolean found = false; int itemPrice; String itemDescription; // Search for items in ArrayList while ( (!found) && (i < cartItems.size()) ) { if (cartItems.get(i).getName().equals(item.getName())) { pos = i; found = true; itemPrice = cartItems.get(i).getPrice(); item.setPrice(itemPrice); itemDescription = cartItems.get(i).getDescription(); item.setDescription(itemDescription); cartItems.set(pos, item); break; } //End of inner if ++i; } //End of While if (!found) { System.out.println("Item not found in cart. Nothing removed."); } //End of outer if } //End of modifyItem //getNumItemsInCart(). Returns quantity of all items in cart. Has no parameters. public int getNumItemsInCart() { int quantity = 0; for (int i = 0; i < cartItems.size(); i++){ quantity += cartItems.get(i).getQuantity(); } //End of inner for loop return quantity; } //End of getNumItemsInCart. //getCostOfCart(). Determines and returns the total cost of items in cart. Has no parameters. public int getCostOfCart() { int totalCost = 0; int indCost; for(int i = 0; i < cartItems.size(); i++){ indCost = cartItems.get(i).getPrice() * cartItems.get(i).getQuantity(); totalCost += indCost; } //End of inner For loop return totalCost; } //End of getCostOfCart() //printTotal(). Outputs total of objects in cart. public void printTotal(){ System.out.println(customerName + "'s Shopping Cart - " + currentDate); System.out.println("Number of Items: " + getNumItemsInCart()); System.out.println(""); if (cartItems.isEmpty()){ System.out.println("SHOPPING CART IS EMPTY"); } //End of if else { for (int i = 0; i < cartItems.size(); i++){ cartItems.get(i).printItemCost(); }// End of inner For } // End of else System.out.println(); System.out.println("Total: $" + getCostOfCart()); } //End of printTotal public void printDescriptions(){ System.out.println(customerName + "'s Shopping Cart - " + currentDate); System.out.println(""); System.out.println("Item Descriptions"); for (int i = 0; i < cartItems.size(); i++){ cartItems.get(i).printItemDescription(); }// End of for } //End of printDescriptions //End of public member Methods } //End class /* Type code here. */ public class ItemToPurchase{ private String itemName; private int itemPrice; private int itemQuantity; private String itemDescription; //Default Constructor public ItemToPurchase(){ itemName = "none"; //Initialized in default constructor to "none" itemPrice = 0; //Initialized in default constructor to 0 itemQuantity = 0; //Initialized in default constructor to 0 itemDescription = "none"; //Initialized in default constructor to "none" } //End of Default Constructor //Parameterized Constructor public ItemToPurchase(String itemN, String itemDesc, int itemP, int itemQ){ itemName = itemN; itemPrice = itemP; itemQuantity = itemQ; itemDescription = itemDesc; }// End of Parameterized Constructor //Mutators public void setName(String itemN){ itemName = itemN; } public void setPrice(int itemP){ itemPrice = itemP; } public void setQuantity(int itemQ){ itemQuantity = itemQ; } public void setDescription(String itemDesc){ itemDescription = itemDesc; } //Mutators End //Gettors public String getName(){ return itemName; } public int getPrice(){ return itemPrice; } public int getQuantity(){ return itemQuantity; } public String getDescription(){ return itemDescription; } //Gettors End //public member Methods public void printItemCost(){ System.out.println(itemName + " " + itemQuantity + " @ $" + itemPrice + " = $" + itemQuantity*itemPrice); } public void printItemDescription(){ System.out.println(itemName + ": " + itemDescription); } //End of public member Methods } //End Class
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |