Java: Both if and else statements run - java

I am trying to refector a 2D array project to include a search method to clean up the code in my main method. However, when I enter a valid name it can find the first row of data but will also print the else statement. If I enter a valid name for second row it will sometimes return it after printing the else statement.
I've tried rewriting the code, creating a return variable for the method, using a nested loop, modifying the return array value.
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("==== Family Affair ====");
System.out.println("How many members will you add?");
int number = scan.nextInt(); scan.nextLine();//scan.nextLine() ad hoc scan fix
//2D Array number of rows by scan/number input
String[][] familyData = new String[number][2];
//for loop captures input column data for each row
//nested loop created duplicate output
for (int i = 0; i < familyData.length; i++) {
System.out.print("\tName: ");
familyData[i][0] = scan.nextLine();
System.out.print("\tState: ");
familyData[i][1] = scan.nextLine();
System.out.println(" ");
}
System.out.println(" ");//extra space
printData(familyData);//call printData() method
findData(familyData);//call findData() method
}
public static void printData(String[][] data) {
for (int i = 0; i < data.length; i++) {
System.out.print("\tName: " + data[i][0] + " ");
System.out.print("\tState: " + data[i][1] + " ");
System.out.println(" ");
}
}
public static String[] findData(String[][] data) {
System.out.println("SEARCH...");
System.out.println("First Name: ");
String name = scan.nextLine();
String[] resultData = new String[0];
for (int i = 0; i < data.length; i++) {
if (name.equals(data[i][0])) {
System.out.println("--- Search Results ---");
System.out.println("\tName: " + data[i][0]);
System.out.println("\tState: " + data[i][1]);
}else {
System.out.println("Nothing found. Try Again");
System.out.println("First Name: ");
name = scan.nextLine();
}
}
return resultData; //returned as String[] results = findData(param);
}

Let me suggest the use of List<>
import java.util.ArrayList;
import java.util.List;
private static List<String[]> findData(String[][] source, String search)
{
final List<String[]> data = new ArrayList<>();
for (String[] array : source)
{
if (search.equals(array[0]))
{
data.add(array);
}
}
return data;
}
And here is an example of use
public static void main(String args[])
{
String[][] familyData = new String[2][2];
familyData[0][0] = "Sulabha";
familyData[0][1] = "Married";
familyData[1][0] = "Bertram";
familyData[1][1] = "Single";
List<String[]> data = findData(familyData, "Sulabha");
if (data.size() == 0)
{
System.out.println("Nothing found.");
}
else
{
for (String[] item : data)
{
System.out.println("--- Search Results ---");
System.out.println("\tName: " + item[0]);
System.out.println("\tState: " + item[1]);
}
}
}

Related

How to Add Sorting with Method and Array in Java

How to display the most fruit with the name and lots of fruit? Can you help me guys, I confusion to add method with sorting in this code. Thank you :D
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the lots of fruit: ");
int numberOfFruit = userInput.nextInt();
String[] fruitName = new String[numberOfFruit];
int[] lotsOfFruit = new int[numberOfFruit];
nameAndLotsOfFruit(userInput, numberOfFruit, fruitName, lotsOfFruit);
}
static void nameAndLotsOfFruit(Scanner userInput, int numberOfFruit, String[] nameFruit, int[] lotsOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
System.out.print("Enter the name of fruit " + (i + 1) + ": ");
nameFruit[i] = userInput.next();
System.out.print("Enter the lots of fruit " + nameFruit[i] + ": ");
lotsOfFruit[i] = userInput.nextInt();
}
}
static int theMostFruit(int numberOfFruit, String[] nameFruit, int[] lotsOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
....
}
}
You are holding name and amount informations in 2 different collections thus making it complexer to handle it. There are many ways to do it but I would've done:
Key-Value pair with fruit names as key and amounts as value
Create a custom class to hold the information
I would go for the second option now
public class FruitCounter {
static List<Fruit> listFruit = new ArrayList<>();
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the lots of fruit: ");
int numberOfFruit = userInput.nextInt();
nameAndLotsOfFruit(userInput, numberOfFruit);
theMostFruit();
}
static void nameAndLotsOfFruit(Scanner userInput, int numberOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
Fruit fruit = new Fruit();
System.out.print("Enter the name of fruit " + (i + 1) + ": ");
fruit.setName(userInput.next());
System.out.print("Enter the lots of fruit " + fruit.getName() + ": ");
fruit.setAmount(userInput.nextInt());
listFruit.add(fruit);
}
}
static void theMostFruit() {
Fruit mostFruit = listFruit
.stream()
.max(Comparator.comparing(Fruit::getAmount))
.orElse(null);
if (mostFruit != null)
{
System.out.print(MessageFormat.format("{0} has the highest amount with {1} pieces.", mostFruit.getName(), mostFruit.getAmount()));
}
}
static class Fruit
{
private String Name;
private int Amount;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
}
}
Please check where I use stream inside the method theMostFruit. It does the job for me. Altough if you have 2 fruits with the same amount, it would give you only one. I suggest you to handle that case by yourself as a practice with java streams.

I'm getting a null pointer exception error and I can't find the source

I'm creating a program where an airport worker can input plane and flight information, after which airport users can print out the plane and flight information that was input. After running the first method startAirportPanel(), and typing 1 into the reader scanner to add plane information, I would get a null pointer exception error after the plane ID and plane capacity are entered.
outcome:
Airport panel
---------------
Choose operation:
[1] Add airplane
[2] Add flight
[x] Exit
1
Give plane ID:
GHUA-HG
Give plane capacity:
22
After typing in 22 here and pressing enter, I would get the null pointer exception.
Here is the object flights:
import java.util.ArrayList;
public class Flights {
public HashMap<String,Integer> plane = new HashMap<String,Integer>();
public HashMap<String,String> flight = new HashMap<String,String>();
public Flights(){
this.plane = plane;
this.flight = flight;
}
public void planeMap(String id, Integer capacity){
plane.put(id, capacity);
}
public void flightMap(String id, String departure, String destination){
String flight1 = departure + "-" + destination;
flight.put(id, flight1);
}
public ArrayList planeList(){
ArrayList<String> keylist = new ArrayList<String>(plane.keySet());
ArrayList<Integer> valuelist = new ArrayList<Integer>(plane.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0 ; i < keylist.size() ; i++){
newlist.add(keylist.get(i) + " (" + valuelist.get(i) + ")");
}
for(int i = 0 ; i < newlist.size() ; i++){
System.out.println(newlist.get(i));
}
return newlist;
}
public ArrayList flightList(){
ArrayList<String> keylist = new ArrayList<String>(flight.keySet());
ArrayList<String> valuelist = new ArrayList<String>(flight.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0; i < keylist.size(); i++){
newlist.add(keylist.get(i) + " (" + plane.containsKey(keylist.get(i)) + ") " + "(" + valuelist.get(i) + ")");
}
for(int i = 0; i < newlist.size() ; i++){
System.out.println(newlist.get(i));
}
return newlist;
}
public int planeInfo(String id){
if(plane.containsKey(id)){
return plane.get(id);
}
return 0;
}
}
And here is the userinterface:
import java.util.HashMap;
import java.util.Scanner;
import java.util.ArrayList;
public class UserInterface {
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
public void startFlightService(){
System.out.println("Flight service ");
System.out.println("--------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[x] Print Quit");
if(reader.equals("x")){
break;
}
if(Integer.parseInt(reader.nextLine()) == 1){
printPlane();
}
if(Integer.parseInt(reader.nextLine()) == 2){
printFlight();
}
if(Integer.parseInt(reader.nextLine()) == 3){
printPlaneInfo();
}
else continue;
}
}
public void startAirplanePanel(){
System.out.println("Airport panel");
System.out.println("---------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[x] Exit");
String input = reader.nextLine();
if(Integer.parseInt(input) == 1){
addPlane();
} if(Integer.parseInt(input) == 2){
addFlight();
}
if(input.equals("x")){
break;
}
}
}
public void addPlane(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
fly.planeMap(id,capacity);
}
public void addFlight(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String departure = reader.nextLine();
System.out.println("Give destination airport code: ");
String destination = reader.nextLine();
fly.flightMap(id,departure,destination);
}
public void printPlane(){
for(int i = 0; i < fly.planeList().size(); i++){
System.out.println(fly.planeList());
}
}
public void printFlight(){
for(int i = 0; i < fly.flightList().size(); i++){
System.out.println(fly.flightList());
}
}
public void printPlaneInfo(){
System.out.print("Give plane ID: ");
String id = reader.nextLine();
System.out.println(id + " (" + fly.planeInfo(id) + ")");
}
}
Lastly, the main class to start the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Write your main program here. Implementing your own classes will be useful.
Scanner reader = new Scanner(System.in);
Flights flightss = new Flights();
UserInterface hello = new UserInterface();
hello.startAirplanePanel();
}
}
```
This part of your constructor makes no sense:
this.fly = fly;
this.reader = reader;
the reader already is instantiated, so you just replace the current value with: the current value.
The fly, however, isn't instantiated. So, you are just setting null to null.
Whatever call you make on fly, will cause an NPE.
Remove the this.reader = reader; and change the line about fly with an actual instantiation.
EDIT:
So, your constructor should be something like:
public UserInterface(){
this.fly = new Flights();
}
I would also re-check your Flights constructor.
The part of the code that is problematic is ( in the UserInterface class ):-
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
Only fly variable type (Flights) is declared without any assignment of the Flights class object.
Fix this using the 'new' keyword for instantiation of the Flights class:-
private Flights fly = new Flights();
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = fly;
this.reader = reader;
}
However code can be refactored in a better way as suggested by #Stultuske.

How to add objects to arraylist with another class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically my professor told me to make use of arraylist? I don't get his point to be honest.. i think he wants me to add objects to arraylist? which right now, I really have no idea how to do it..
My code is running and is really fine. However, he still wanted me to make use of arraylist to make it look better?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ahaprogram2;
import java.util.ArrayList;
import java.util.Scanner;
public class AhaProgram {
public static Container container1 = new Container("Container 1: ");
public static Container container2 = new Container("Container 2: ");
public static Container container3 = new Container("Container 3: ");
public static Container container4 = new Container("Container 4: ");
public static Container container5 = new Container("Container 5: ");
public static boolean loop = false;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Hello! This is the AHA Program of Jalosjos,
Parreno and Alfonso");
System.out.println("Please type the letter of your option");
while (loop != true) {
showOptions();
InputHandler();
}
}
public static void InputHandler() {
Scanner reader = new Scanner(System.in);
String optionletter = reader.nextLine();
if (optionletter.equals("A")) { // OPTION A
System.out.println("There are 5 containers.. What container
will you name? ");
System.out.print("Type the number of your container: ");
String contInput = reader.nextLine();
if (contInput.equals("1")) {
System.out.print("Input the name of Container 1: ");
String ContInp1 = reader.nextLine();
container1.renameCont(ContInp1);
container1.printContainer();
} else if (contInput.equals("2")) {
System.out.print("Input the name of Container 2: ");
String ContInp2 = reader.nextLine();
container2.renameCont(ContInp2);
container2.printContainer();
} else if (contInput.equals("3")) {
System.out.print("Input the name of Container 3: ");
String ContInp3 = reader.nextLine();
container3.renameCont(ContInp3);
container3.printContainer();
} else if (contInput.equals("4")) {
System.out.print("Input the name of Container 4: ");
String ContInp4 = reader.nextLine();
container4.renameCont(ContInp4);
container4.printContainer();
} else if (contInput.equals("5")) {
System.out.print("Input the name of Container 5: ");
String ContInp5 = reader.nextLine();
container5.renameCont(ContInp5);
container5.printContainer();
}
}
if (optionletter.equals("B")) { // for option B
System.out.println("Which container will you use?");
System.out.print("Type a number for the container: ");
String contforAdd = reader.nextLine();
if (contforAdd.equals("1")) {
System.out.print("How many cans will you add?: ");
int numofCans1 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans1; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container1.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("2")) {
System.out.print("How many cans will you add?: ");
int numofCans2 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans2; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container2.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("3")) {
System.out.print("How many cans will you add?: ");
int numofCans3 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans3; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container3.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("4")) {
System.out.print("How many cans will you add?: ");
int numofCans4 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans4; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container4.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("5")) {
System.out.print("How many cans will you add?: ");
int numofCans5 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans5; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container5.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
}
if (optionletter.equals("C")) {
System.out.println("Which container will you use?");
System.out.print("Type a number for the container: ");
String contforRemove = reader.nextLine();
if (contforRemove.equals("1")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container1.RemoveCan(canRemove);
}
if (contforRemove.equals("2")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container2.RemoveCan(canRemove);
}
if (contforRemove.equals("3")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container3.RemoveCan(canRemove);
}
if (contforRemove.equals("4")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container4.RemoveCan(canRemove);
}
if (contforRemove.equals("5")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container5.RemoveCan(canRemove);
}
}
if (optionletter.equals("D")) {
showOptionsDisplay();
System.out.print("Type a letter: ");
String letterDisplay = reader.nextLine();
if (letterDisplay.equals("A")) {
container1.printContents();
System.out.println("");
}
if (letterDisplay.equals("B")) {
container2.printContents();
System.out.println("");
}
if (letterDisplay.equals("C")) {
container3.printContents();
System.out.println("");
}
if (letterDisplay.equals("D")) {
container4.printContents();
System.out.println("");
}
if (letterDisplay.equals("E")) {
container5.printContents();
System.out.println("");
}
if (letterDisplay.equals("F")) {
container1.printContents();
System.out.println("");
container2.printContents();
System.out.println("");
container3.printContents();
System.out.println("");
container4.printContents();
System.out.println("");
container5.printContents();
System.out.println("");
}
}
if (optionletter.equals("E")) {
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Thank you for using our program. MWAH!");
loop = true;
}
}
public static void showOptions() {
System.out.println("A = Name Containers");
System.out.println("B = Add Cans");
System.out.println("C = Remove Cans");
System.out.println("D = Display Cans");
System.out.println("E = Quit");
System.out.print("Type a Letter: ");
}
public static void showOptionsDisplay() {
System.out.println("Pick an Option");
System.out.println("A = Display container 1");
System.out.println("B = Display container 2");
System.out.println("C = Display container 3");
System.out.println("D = Display container 4");
System.out.println("E = Display container 5");
System.out.println("F = Display all containers");
}
}
Here is the other class
package ahaprogram2;
import java.util.ArrayList;
import java.util.Scanner;
public class Container {
Scanner reader = new Scanner(System.in);
public ArrayList<String> CanContainer = new ArrayList<String>();
public int Contsizep;
public String contName;
public String changeName;
public Container(String contname){
this.contName = contname;
}
public void AddCan(String CantoAdd) {
this.CanContainer.add(CantoAdd);
}
public void RemoveCan(String CantoRemove) {
if (this.CanContainer.contains(CantoRemove)) {
this.CanContainer.remove(CantoRemove);
System.out.println("** " + CantoRemove + " Can removed
successfully**");
}
else {
System.out.println("Can cannot be found.. make sure to put the
exact name!!");
}
}
public void renameCont(String changename) {
this.contName += changename;
}
public void printContents() {
System.out.println("Here are the contents of " + contName);
System.out.println("");
for(String counter : this.CanContainer){
System.out.println(counter); }
}
public void printContainer() { // for OPTION A ONLY
System.out.println("CONTAINER NAME SUCCESSFUL: ** " + contName +
"**");
}
}
I just would like to put everything to an arraylist
please help.. again my professor doesn't teach us face to face that's why
I'm really trying my best to watch videos in youtube and to ask here also..
A lot of your code seems to predicate on interacting one of five Container objects in similar (if not identical) ways. To start, you can use an ArrayList to store a list of Container objects, instead of manually declaring each container:
public static ArrayList<Container> containerList = new ArrayList<Container>();
You can then populate this list with new containers using ArrayList.add(E e), combined with a for loop or some other construct:
for (int i = 1; i <= 5; i++) {
Container container = new Container("Container " + i + ": ");
containerList.add(container);
}
Likewise, you can access any particular container using ArrayList.get(int index) (if you know the index) or ArrayList.indexOf(Object o) (if you have a reference to a specific container). This can replace or supplement your conditional statements. For instance, your list of (contInput.equals("X")) statements could be replaced with:
int index = Integer.parseInt(contInput);
System.out.print("Input the name of Container " + index + ": ");
Container container = containerList.get(index - 1); // arrays start at 0, but your numbering starts at 1
String contImp = reader.nextLine();
container.renameCont(contImp);
container.printContainer();
Hope this helps.
You can add your containers to ArrayList like this:
ArrayList<Container> containers = new ArrayList<>();
containers.add(new Container("Container 1: "));
containers.add(new Container("Container 2: "));
containers.add(new Container("Container 3: "));
then get them like this:
Container firstContainer = containers.get(0);
Container secondContainer = containers.get(1);

How to stop on duplicate entry (Java)

I have a simple code that asks a user to input items and stores them into an array. I would like to make it so the program stops running when the last entry is the same as the first.
so for example this would stop the program because Cookie it both the first item in the array and the last. But it's also ok to have duplicates with in the array like "Sugar" in this example:
Enter the item: Cookie
Enter the item: Sugar
Enter the item: Milk
Enter the item: Sugar
Enter the item: Salt
Enter the item: Cookie
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20;
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//Now show your items's name one by one
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Thanks for your help
You can do this by adding a simple if-condition with equals() method. you need do add following if-condition.
if(Temp.equals(arrayOfNames[0])) // readed Temp equals to first element.
Try this code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20,maxItems=0; // total items may vary
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
String Temp=""; // for temporary storage
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
Temp= scan.nextLine();
if(Temp.equals(arrayOfNames[0])){
maxItems=i;
break;
}
else{
arrayOfNames[i]=Temp;
}
}
//Now show your items's name one by one
for (int i = 0; i < maxItems; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Output :-
Enter Item 1 : Cookie
Enter Item 2 : Sugar
Enter Item 3 : milk
Enter Item 4 : Sugar
Enter Item 5 : Salt
Enter Item 6 : Cookie
Item # 1 : Cookie
Item # 2 : Sugar
Item # 3 : milk
Item # 4 : Sugar
Item # 5 : Salt
If you don't know the number of items will be entered by the user then this code will be helpful,
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.print("Enter name:");
String temp = sc.next();
if(al.isEmpty() != true)
{
if(temp.equals(al.get(0)))
break;
}
al.add(temp);
}
for(int i = 0;i<al.size();i++)
{
System.out.println(al.get(i));
}
}
}
More sophisticated OO Program Example:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Grocery {
List<String> basket; // list of items in the basket
//constructor of Grocery with number of items provided
public Grocery(int numberOfItems) {
basket = new ArrayList<>(numberOfItems); // initialize basket
}
/**
* Add item to basket only if it is not similar to the first item
* return true if succeeded otherwise return false if it's duplicate
* #param item
* #return
*/
public boolean addItem(String item) {
if(basket.size()==0) return basket.add(item);
if(!basket.get(0).equals(item)) {
return basket.add(item);
}
return false;
}
/**
* Remove specific item in the basket
* or all items by name if "all" is true
* #param item
*/
public void removeItem(String item, boolean all) {
if(all) {
for(String i : basket) {
if(i.equals(item)) {
basket.remove(i);
}
}
}else {
basket.remove(item);
}
}
// method to empty the basket
public void emptyBasket() {
basket.clear();
}
/**
* Override toString() to provide your own
* textual representation of the basket
*/
#Override
public String toString() {
String s = "";
for(int i=0; i<basket.size(); i++) {
s += "Item #" + (i+1) + " : " + basket.get(i) + "\n";
}
return s;
}
// TEST
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems=0;
System.out.print("Enter How Many Items: ");
try {
numOfItems = Integer.parseInt(scan.nextLine().trim());
}catch(NumberFormatException e) {
System.out.print("Number of items you entered is invalid!");
System.exit(0);
}
Grocery grocery = new Grocery(numOfItems);
for (int i = 0; i < numOfItems; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
if(!grocery.addItem(scan.nextLine())) {
System.out.println("First Item Duplicate Detected!");
//break;
System.exit(0);
};
}
scan.close();
System.out.println(grocery.toString());
}
}
Test
Sounds to me like you should be able to do a if statement in here to find out if array[0] = array[i]
if (i > 0 && (arrayOfNames[0] == arrayOfNames[i])) {
// do something
}
Simply add a condition that if the current element matches first element, then break out of the for loop.
String first=null;
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
if (i==0){
first=arrayOfNames[i];
}else{
if(first==arrayOfNames[i]){break;}
}
}
Just change your for loop condition to:
for (int i = 0; i == 0 || arrayOfNames[i] != arrayOfNames[0]; i++)

Output Should be What is in the Array

I'm doing a library system which once I input a book name, and found inside the array, the out put would be "the book was returned" . But every time I input the name of one the books listed in the array, it still say that "the book is out of order". How can I solve this problem?
import java.util.Scanner;
public class NewClass {
public static void main (String args[]){
Scanner book = new Scanner(System.in);
String [] library = new String [4];
library [0] = "Brazil";
library [1] = "Japan";
library [2] = "China";
library [3] = "India";
String bookEntry = " ";
int day;
int x = 2;
int penalty;
for (int i = 0; i < library.length; i++){
System.out.println("Insert name of the book: ");
bookEntry= book.next();
if (bookEntry == library[i]){
System.out.println("The book was returned");
}else if (bookEntry != library[i]){
System.out.println("The book is out of order");
System.out.println("\n" + bookEntry.toUpperCase()+ " " + "is out since: ");
day = book.nextInt();
if (day > x){
penalty = day*20;
System.out.println("Total fine: " + penalty);
}else{
System.out.println("Not yet due.");
}
}
}
}
}
In Java, you don't compare 2 strings by ==.
Instead you use, .equals() method of class String.
==            -> is a reference comparison, i.e. both objects point to the same memory location
.equals()  -> evaluates to the comparison of values in
the objects
More on this here
Corrected code below :
import java.util.Scanner;
public class NewClass {
public static void main(String args[]) {
Scanner book = new Scanner(System.in);
String[] library = new String[4];
library[0] = "Brazil";
library[1] = "Japan";
library[2] = "China";
library[3] = "India";
String bookEntry = " ";
int day;
int x = 2;
int penalty;
System.out.println("Insert name of the book: ");
bookEntry = book.next();
boolean present = false;
for (int i = 0; i < library.length; i++) {
if (bookEntry.equals(library[i])) {
present = true;
break;
}
}
if (present) {
System.out.println("The book was returned");
} else {
System.out.println("The book is out of order");
System.out.println("\n" + bookEntry.toUpperCase() + " " + "is out since: ");
day = book.nextInt();
if (day > x) {
penalty = day * 20;
System.out.println("Total fine: " + penalty);
} else {
System.out.println("Not yet due.");
}
}
}
}
Working code here
UPDATE : I have changed the code.

Categories

Resources