I have a home work that requires user to input the name and process of products using for loop and print the price and name of the most expensive product. I have already figure out using the loop and transferring the variables to the constructor.
int numberOfProducts; //user input
for (i=0; i<=numberOfProducts; i++)
{
System.out.print("Name of product" + i);
System.out.println("price of product" +i);
Product myProduct= new Product (name, price);
//enter code here
}
I know I can write something like:
If max<price
price=max;
to find the max, but, have no idea how to incorporate the name when I print the maximum price.
Could you please give me a hint???
Thanks!
You just need to keep both the maximum price and the name of the product with that maximum price. For example,
Product[] products = // your products.
Product mostExpensiveProduct = product[0];
for (Product product : products) {
if (product.getPrice() > mostExpensiveProduct.getPrice()) {
mostExpensiveProduct = product;
}
}
System.out.println("Most expensive product is " + mostExpensiveProduct.getName() + " with price " + mostExpensiveProduct.getPrice());
Related
I doing a bigger school project (first part of basic objective programming in java - so not touched extended, polyphorism etc yet, thats next part), but run in to a small problem and tried for couple of days to find solution (thru books and internet). I constructed different ArrayLists in one class and different classes (at least two) should get access to them.
public class Customer
{
public void subMenuCustomer()
{
............code............
int subMenuCust;
ServiceLogic addCustomer = new ServiceLogic();
ServiceLogic listAllCustomers = new ServiceLogic();
while(true)
{
System.out.println("Please Choose your preference: ");
System.out.println("Create account, press \"1\": ");
System.out.println("Get list of clustomers, press \"2\": ");
System.out.println("Log out, press \"0\": ";
subMenuCust = input.nextInt();
switch(subMenuCust)
{
case 1 ://Call method createCustomer in class ServiceTech to add new customers
addCustomer.createCustomer(name, lastname, ssNo);
break;
case 3
listAllCustomers.getCustomer();
............more code..............
}
}
When user has added details (social secuity number, name and lastname) it is stored in seperate ArrayList. These three ArrayList are added(merge/concat) together to a fourth ArayList, listCustomer , so that all elements from the three ArrayList end up in same index [101 -54 Clark Kent, 242-42 Linus Thorvalds, ...].
import java.util.ArrayList;
import java.util.Scanner;
public class ServiceLogic
{
//Create new ArrayLists of Strings
private ArrayList<String> listSSNoCustomers = new ArrayList<>();
private ArrayList<String> listNameCustomers = new ArrayList<>();
private ArrayList<String> listLastnameCustomers = new ArrayList<>();
private ArrayList<String> listCustomers;
Scanner input = new Scanner(System.in);
public boolean createCustomer(String name, String lastname, String ssNo) //
{
System.out.println("Write social security number; ");
ssNo = input.next();
//loop to check that it is a uniq social security number
for(String ssNumber : listSSNoCustomers)
{
if (ssNumber.equals(ssNo))
{
System.out.println("This customer already exist. Must be uniq social security number.");
return true;
}
}
//If social security number is not on list, add it
//and continue add first name and surname
listSSNoCustomers.add(ssNo);
System.out.println(ssNo);
System.out.println("Write firstname; ");
name = input.next();
listNameCustomers.add(name);
System.out.println(name);
System.out.println("Write lastnamame; ");
surname = input.next();
listSurnameCustomers.add(lastname);
System.out.println(lastname);
return false;
}
public void setListCustomer(ArrayList<String> listCustomers)
{
this.listCustomers = listCustomers;
}
public ArrayList<String> getCustomer()
{
//ArrayList<String> listCustomers = new ArrayList<>();
for(int i = 0; i <listSSNoCustomers.size(); i++)
{
listCustomers.add(listSSNoCustomers.get(i) + " " + listNameCustomers.get(i) + " " + listFirstnameCustomers.get(i));
}
System.out.println("customer" + listCustomers);
return listCustomers;
}
}
According to the specification we got, when user want to see list of all customer the outputs should be in format [666-66 Bruce Wayne, 242-42 Linus Thorvalds, ...].
When user (staff) choose to enter details in class Customer ( Case 1 ) it works and elements get stored in the Arraylists for social security numbers, name and lastname (have checked that) .
The problem: when I run I can add customers, but when I try to get a list of customer the output: [] . I tried different solution, but same output only empty between the brackets.
So the question, how do I get ouput to work when user choose case 2 to get a list of all cutomers?
I am trying to make a practice program for a bookstore clerk that allows the clerk to add, remove, edit, and search for books in its database. I have all but made the entire program however I am getting stuck on 2 errors. It is a total of 234 lines of code in all so I will try to shorten it to the relevant parts to make it easier on those willing to help me. I am using Eclipse with JDE and JDK 10. The Eclipse project was initiated using the JavaSE-10 execution environment as far as I am aware. Below are the 2 methods causing the errors.
public class Bookstore {
public static void main(String[] args) {
try(
//Creating table connection and statement
Connection conn = DriverManager.getConnection("***********",
"****", "*********"); //Please note that I blocked out the actual connection information here
Statement stmt = conn.createStatement();
){
Scanner input = new Scanner(System.in);
int selection = 0;
//Menu for action selection and user input
while(selection != 5) {
System.out.println("Please enter the number corresponding to the action you would like to take:\n"
+ "1. Enter book\n"
+ "2. Update book\n"
+ "3. Delete book\n"
+ "4. Search books\n"
+ "5. Exit");
selection = input.nextInt();
//Selection sorting
if(selection == 1) {
//Collecting book information
System.out.println("Please enter the Title of the book you would like to put into the system: ");
String title = input.next();
System.out.println("Please enter the Author of said book: ");
String author = input.next();
System.out.println("Please enter the number of said book currently in stock: ");
int qty = input.nextInt();
//Sending info to the addBook method
addBook(title, author, qty, stmt);
} else if(selection == 2) {
//Collecting book information
System.out.println("Please enter the id of the book you would like to update: ");
int id = input.nextInt();
//Sending info to the updateBook method
updateBook(id, stmt);
} else if(selection == 3) {
//Collecting book information
System.out.print("Please enter the id of the book you would like to delete from the system: ");
int id = input.nextInt();
//Sending info to deleteBook method
deleteBook(id, stmt);
} else if(selection == 4) {
searchStore(stmt);
} else if(selection == 5) {
System.out.println("Goodbye");
input.close();
} else { //Invalid entry handler
System.out.println("Sorry, that isn't a valid selection.");
}
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
} //This is the line giving me the error "Syntax error on token "}", delete this token"
Now I have already done some research regarding the error at the bottom of this block of code. As far as I can tell I am not missing any brackets and there are no variables or anything being created outside of a class that would cause this error. The only other solution I have been able to find is that "Eclipse is just being weird".
My second error comes from this block of code:
public static void resultSetPrinter(ResultSet rset) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n\n");
}
if(rset == null) {
System.out.println("No records for the entry could be found.");
}
} //This is the line giving me the "Syntax error, insert "}" to complete ClassBody" error
I have also done some research regarding the error at the bottom of this block and when I do remove the bracket as requested the error just jumps up to the method before this one. I haven't included the other 4 methods in the class to try and reduce the headache of running through all this code since they aren't giving me errors. Any help would be greatly appreciated at this point, I am completely stumped.
Thanks mainly to Elliott Frisch I have found my answer. Essentially I needed to put all my methods into my main class by the name of Bookstore. I moved the } to the end of my program and added try catch statements for each method. For example I changed the last code block I put in my question to:
public static void resultSetPrinter(ResultSet rset) {
try {
if(rset.next()) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("Qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n");
}
} else {
System.out.println("No records for the entry could be found.\n");
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
You'll also note that I added an if else statement to check if the ResultSet rset was empty, if it wasn't I proceeded as normal and if it was I printed a simple message to let the user know nothing was found.
Thank you both Elliott Frisch and Marco13 for the asssistance.
I am supposed to create an output similar to this:
I have organized my data into an array. To put it simply, I have organized it to
with 8 different POIBook with its individual data.
POIBook[i] = new POI(Type, Place, Rating)
I have no problems calling the right array according to the user input into a JOptionpane display.
However, I have problems trying to determine the total number of search and the search result the user is currently at. Eg. Search 1 of 3
How do I get the total number of the search result and the number the user is currently at?
Edit: To add in the context of the question.
The user will enter a search query in JOptionpane and it will search and return the array containing the search result. For example, searching for "Excitement" will return POIBook[4] , [5] and [6] as a JOptionpane display and as per the output expected in the picture above.
Need help on the following:
How do I show that that 'Search Result - 1/3' when POIBook [4] is returned? and 'Search Result - 2/3' when POIBook[5] is returned etc.?
At the point of display, we will need to know there are 3 results of "excitement" type and it is currently showing the 1st result out of 3.
public static void dataPOI() {
POIBook[0] = new POI("Sightseeing", "River Safari","Wildlife, Panda Bear, Cruise",4.0);
POIBook[1] = new POI("Sightseeing", "Singapore Flyer","Fly!",3.5);
POIBook[2] = new POI("Sightseeing", "Gardens by The Bay","Flower Dome, Cloud Forest",3.5);
POIBook[3] = new POI("Shopping", "Orchard Road","Ion, Mandarin Gallery",4.0);
POIBook[4] = new POI("Excitement", "Universal Studios","Battlestar Galactica, Puss in Boots",4.5);
POIBook[5] = new POI("Excitement", "Marina Bay Sands","Casino, Sky Park Observation Deck",4.0);
POIBook[6] = new POI("Excitement", "Resorts World Sentosa","Trick Eye Museum, Adventure Cove",4.5);
POIBook[7] = new POI("Night Life", "Night Safari","Wildlife, Tram Ride",4.5);
}
My code is as follows.
public static void search() {
String search = JOptionPane.showInputDialog(null, "Please enter your type of attraction", "Place of Interest",
JOptionPane.QUESTION_MESSAGE);
for (int i = 0; i<POIBook.length; i++) {
if(search.equalsIgnoreCase(POIBook[i].type)) {
Object[] options = { "Next >", "Return to Menu" };
int select = JOptionPane.showOptionDialog(null, "Place of interest " + (i+1) + " of 8\n" + POIBook[i].display() +
"\nPress Next for next Place of Interest \n" + "To return, press Return to Menu \n", "Display Places of Interest in Sequence",
JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE, POIBook[i].icon, options, options[1]);
if (select == 1) {
return;
}
}
}
}
If the user key in 4 I wish to pop up a message to inform the user that is no data found for user id "4" in the array list.
But when the user key in 4 there is 3 no data found appear.
User usr1 = new User(1,"Ken", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Mark", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Ong", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
String answer ="";
do{
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter user ID");
int userid = scan.nextInt();
for(User uid: ulist){
if(userid == uid.getUID()){
System.out.println(uid.getUID() +", " + uid.getName() +", " + uid.getAge() +" years old, " + uid.getWeight() +"kg");
}else{
System.out.println("no data found");
}
}
System.out.println("Continue(Y/N)");
answer = scan.next();
}while(answer.equalsIgnoreCase("y"));
current result:
no data found
no data found
no data found
Result that i wish:
no data found
Remove else { System.out.println("no data found"); } from the loop and put it outside. The for loop intent is to find, to lookup the correct user.
Once found you may use it: you have to declare a variable of type User before loop, initialized to null and if it's null after lookup, you have to print the message 'not found'.
You get no data found 3 times because you print it in the cycle: for every user in the list, if his id doesn't match specified id, System.out.println("no data found"); You can avoid this modifying your cycle or writing a method that fidns user by id.
User found;
for (User uid : ulist) {
if (userid == uid.getUID()) {
found = uid;
break; // assuming that ids are unique
}
}
if (found != null) {
System.out.println(found.getUID() +", " + found.getName() +", " + found.getAge() +" years old, " + found.getWeight() +"kg");
} else {
System.out.println("no data found");
}
You have problem in your logic.
in your for loop you should have a break statement, in case there is no data found.
else {
System.out.println("no data found");
break;
}
This is what my code does.
(1.) Open chrome browser and go to footlocker.ca
(2.) Click on the Mens button
(3.) Select 1 random product from the list of 60
(4.) Print the product name and price
(5.) Print all available sizes for the selected product (avaSizes)
(6.) Go back to the products page
(7.) Select a 2nd random product from the list of 60
(8.) Print the product name and price
(9.) Print all available sizes for the selected product (avaSizes)
(10.) Close chrome browser
My problem is that it fails to read the available sizes for the product. I think my problem is in the xpath but I am not to sure as I have tinkered with various xpath's so it may be my code that is the problem. The method is called (avaSizes). If someone can help it would be great. I am doing this for practice so if anyone has some real time job scenario test cases that I could add on to this code it would help me a lot. Thanks.
public class FootlockerExample {
WebElement next;
WebDriver driver = new ChromeDriver();
public void productOne (){
// Open Chrome Browser
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Working\\Workspace\\SeleniumProject\\chromedriver.exe");
// Open Footlocker website and maximize window
driver.get("http://www.footlocker.ca/");
driver.manage().window().maximize();
// Find button element 'Mens' and click
next = driver.findElement(By.xpath("//*[#id='global-nav']/ul/li[1]/a"));
next.click();
// Select a random product
selectRandomProduct();
// Print out the product name and price
String productName = driver.findElement(By.xpath("//*[#id='product_form']/div/span[2]/div/div[1]")).getText();
String Price = driver.findElement(By.xpath("//*[#id='product_form']/div/span[2]/div/div[2]")).getText();
System.out.println("The 1st randomly selected product is " + productName + " and it's cost is " + Price + ".");
// Print all available product sizes
avaSizes();
// Execute new method
productTwo();
}
public void productTwo(){
// Go back a browser page
driver.navigate().back();
// Select a new random product
selectRandomProduct();
// Print out the product name and price
String productName = driver.findElement(By.xpath("//*[#id='product_form']/div/span[2]/div/div[1]")).getText();
String Price = driver.findElement(By.xpath("//*[#id='product_form']/div/span[2]/div/div[2]")).getText();
System.out.println("The 2nd randomly selected product is " + productName + " and it's cost is " + Price + ".");
// Print all available product sizes
avaSizes();
driver.close();
}
public void selectRandomProduct(){
// Find and click on a random product
List<WebElement> allProducts = driver.findElements(By.xpath("//*[#id='endecaResultsWrapper']/div[3]//img"));
Random rand = new Random();
int randomProduct = rand.nextInt(allProducts.size());
allProducts.get(randomProduct).click();
}
public void avaSizes(){
// Find all the available shoe sizes for each randomly selected product
List<WebElement> avaSizes = driver.findElements(By.xpath("//*[#id='product_sizes']"));
int totalSizes = 0;
for(int i=0; i<avaSizes.size(); i++){
if(avaSizes.get(i).isEnabled()==true){
avaSizes.get(i).getText();
System.out.println(avaSizes);
totalSizes++;
}else{
System.out.println("Out of stock in all sizes.");
}
}
System.out.println("This product is available in: " + totalSizes + " sizes.");
}
public static void main(String[] args) {
FootlockerExample obj1 = new FootlockerExample();
obj1.productOne();
}
}
I see that the dropdown element has an id and is of type Select.
You can work with it using the Select object:
Select select = new Select(driver.findElement(By.id("product_sizes")));
List<WebElement> availableSizes = select.getOptions();
for (WebElement size : availableSizes) {
System.out.println(size.getText());
}
With a little help from Marius D above, I have figured out the problem and fixed my code.
Here is my fixed answer for future in case someone is stuck on the same issue.
public void avaSizes(){
Select select = new Select(driver.findElement(By.id("product_sizes")));
// Find all the available shoe sizes for each randomly selected product
List<WebElement> avaSizes = select.getOptions();
int totalSizes = 0;
for(WebElement size:avaSizes){
if(size.isEnabled()==true){
System.out.println(size.getText());
totalSizes++;
}else{
System.out.println("Out of stock in " + size.getText());
}
}
System.out.println("This product is available in: " + totalSizes + " sizes.");
}