Elements are not removed from list - java

i am newbee in java and trying to remove elements from list array. Have been tried many variants, but always get input error and nothing been deleted from list. Have tried take make condition like: if (list.contains(tch.getSurname()) or something like this, always get error that input error. Hope, you will help me to resolve this problem.
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static Main main = new Main();
/*public static Teachers tch = new Teachers(surname, name);*/
public static List<Teachers> list = new ArrayList<Teachers>();
public static void io(){
Scanner sc = new Scanner(System.in);
String surname = "";
String name = "";
Teachers tch = new Teachers(surname, name);
for (int i=0; i<2; i++) {
surname = sc.nextLine();
name = sc.nextLine();
tch = new Teachers(surname, name);
list.add(tch);
}
for(Teachers nstr : list) {
System.out.println(nstr.toString());
}
for(Teachers t : list) {
String input = sc.nextLine();
if (input == tch.getSurname()) {
list.remove(input);
} else {
System.out.println("Wrong input");
}
}
for(Teachers nstr : list) {
System.out.println(nstr.toString());
}
}
public static void main(String[] args) {
main.io();
}
}
UPDATE:
So i'm tried to use iterator, i've added:
for (Iterator<Teachers> it = list.iterator(); it.hasNext();){
Teachers t = it.next();
if (t.equals(tch.getSurname())){
it.remove();
}
}
and delete:
for(Teachers t : list) {
String input = sc.nextLine();
if (input.equals(tch.getSurname())) {
list.remove(tch);
} else {
System.out.println("Wrong input");
}
}
But it also didn't help me to delete element from list array, it just duplicate my input for list.

Your error is if(input == tch.getSurname(). This compares the exact reference to see if it is the same. Instead, use if(input.equals(tch.getSurname())) to check the contents.
Also change the reference in that loop from tch to t. You are not using the current element in the list rather the one you created to add to the list. Finally change list.remove(input) to list.remove(t). This way the actual element is being removed, no just trying to remove the surname string.
Change your for loop to
Iterator<Teachers> i = list.iterator();
while(i.hasNext()){
Teachers t = i.next();
...
}
Then to remove it just use i.remove()

Now loop works perfectly.
for(Teachers t : list) {
String input = sc.nextLine();
if (input.equals(t.getSurname())) {
list.remove(t);
} else {
System.out.println("Wrong input");
}
}

Related

reverse a stack and concatenate a popped stack

I'm trying to push any array list to a stack in reverse then concatenate a popped stacked. I getting the information from a file then storing it into an array List. Then i pushed the array List into a stack. now when i print the stack out its just printing the array List how can i pop the stack and concatenate it? here is my code so far
public static LinkedListStack myStack = new LinkedListStack();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
song.add(line = inFile.next());
}
for(int i = 0; i < song.size(); i++)
{
myStack.push1(song);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
if(!myStack.empty())
{
System.out.println(myStack.pop1());
} else
{
System.out.println("Sorry stack is empty");
}
}
output looks like this now :[Mary, had, a, little, lamb, Whose, fleece, was, white, as, snow, Everywhere, that, Mary, went, The, lamb, was, sure, to, go]
I'm trying to get it to look like this:
lamb little a had Mary
snow as white was fleece Whose
went Mary that Everywhere
go to sure was lamb The
i have made a custom class for the push and pop
{
private Node first;
/**
Constructs an empty stack.
*/
public LinkedListStack()
{
first = null;
}
/**
Adds an element to the top of the stack.
#param element the element to add
*/
public void push1(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
/**
Removes the element from the top of the stack.
#return the removed element
*/
public Object pop1()
{
if (first == null) { throw new NoSuchElementException(); }
Object element = first.data;
first = first.next;
return element;
}
/**
Checks whether this stack is empty.
#return true if the stack is empty
*/
public boolean empty()
{
return first == null;
}
class Node
{
public Object data;
public Node next;
}
}
I fixed the problems in your code. Here is the working version along with some comments. This assumes the sentences in the file are separated by new lines and the words are separated by white spaces.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneralTest {
//You want the same ordering for sentences. This collection
//therefore should be a list (or a queue)
//I have not changed the name so you can see how it makes a
//difference
public static List<LinkedListStack> myStack = new ArrayList<>();
public static void main(String[] args)
{
readFileLoadStack();
popStackPrintMsg();
}
public static void readFileLoadStack()
{
File afile; // For file input
Scanner keyboard = new Scanner(System.in); // For file input
String fileName; // To hold a file name
String line;
ArrayList song = new ArrayList<>();
boolean fileNotFound = true;
do
{
// Get a file name from the user.
System.out.println("Enter the name of the file");
fileName = keyboard.nextLine();
// Attempt to open the file.
try
{
afile = new File(fileName);
Scanner inFile = new Scanner(afile);
System.out.println("The file was found");
fileNotFound = false;
while (inFile.hasNextLine())
{
//Here you need to use nextLine() instead of next()
song.add(inFile.nextLine());
}
//This loop is the main location your original code goes wrong
//You need to create a stack for each sentence and add it to the
//list. myStack will hold a list of stacks after this loop is done
for(int i = 0; i < song.size(); i++)
{
String songString = (String) song.get(i);
String[] sga = songString.split(" ");
LinkedListStack rowStack = new LinkedListStack();
for(int j=0; j < sga.length; j++) rowStack.push1(sga[j]);
myStack.add(rowStack);
}
}
catch (FileNotFoundException e)
{
fileNotFound = true;
}
} while (fileNotFound);
}
public static void popStackPrintMsg()
{
//To get all values in a collection you need to
//loop over it. A single if will not work
for(LinkedListStack rs : myStack)
{
//Each entry in the list is a LinkedListStack
//So you can pop them and print the results with
//appropriate separators
while(!rs.empty())
System.out.print(rs.pop1() + " ");
System.out.println();
}
}
}
Now, your code has many other problems. For example, you really should use generics when you create a collection class.
The main problem with your code is that to produce the output you have described, you will need a queue of stacks. I have implemented the concept using ArrayList to show the source of the problem. But if you want to learn data structures (or if this is a homework problem), then you should try implementing and using a queue as well.

Issues with do while loop in java

Having an issue with my do while loop as it doesn't end when STOP is entered. Also I'm not sure if I need to add any exceptions or what not. I know doing toString would be more efficient but the requirement for the program is a for loop when extracting the output.
import java.util.*;
import java.util.ArrayList;
import java.lang.IndexOutOfBoundsException;
public class MyProj
{
public static void main(String[] args)
{
ArrayList <String> MyItems = new ArrayList <String>();
Scanner Scan = new Scanner(System.in);
String Temp;
System.out.println("Please enter the name of an object, repeat as needed, type STOP to end");
do
{
Temp = Scan.nextLine();
if(Temp != "STOP")
{
MyItems.add(Temp);
}
}
while(Temp == "STOP");
for(int x = 0; x <= MyItems.size() - 1; x++)
{
System.out.println(MyItems.get(x));
}
}
}
Try this code:
do
{
Temp = Scan.nextLine();
if(!Temp.equals("STOP"))
{
MyItems.add(Temp);
}
}
while(!Temp.equals("STOP"));
I'd recommend that you change that to equalsIgnoreCase() as #3kings suggested.

Getting size and comparing attribute value from ArrayList in other class

I am trying to create a method which creates a result for a athlete in a competition. I have an ArrayList with the athletes in another class and now I want this method to be able to find the size of the ArrayList and also compare one int attribute of every Athlete with the input number. This is what I have so far, Im really stuck. So my quetions to you are: How do I get my for loop to see the size of the ArrayList athletes? and what is a proper way to check whether or not the input has a matching athlete in the ArrayList(I want it to print out if there is no match)? Thank you
public class ResultList {
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
public ResultList() {
ArrayList<Athlete> temp = new AthleteList().getArrayList();
}
void addResult() {
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
for (int i = 0; i < athletes.size(); i++) {
}
}
}
Other class with the Athlete ArrayList:
public class AthleteList {
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
public AthleteList () {
}
public ArrayList<Athlete> getArrayList() {
return athletes;
}
You should create a variable that points to the AthleteList class. Then you can see that in the addResult method you just get the ArrayList from the AthleteList and call size() on it and iterate over the Athletes and check the completionNumber(You didn't post the Athlete class so I'm assuming there is a completionNumber property). I create a matched variable to hold on to the matched Athlete. After the loop I check to see if one matched and print out the result.
Hope this helps.
public class ResultList
{
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
AthleteList athleteList;
public ResultList()
{
athleteList = new AthleteList();
}
void addResult()
{
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
Athlete matched = null;
List<Athlete> athletes = athleteList.getArrayList();
for(int i = 0; i < athletes.size(); i++)
{
if(athlete.completionNumber == completionNumber)
{
//you found a match!!
matched = athlete;
}
}
if(matched == null)
{
System.out.println("No Match Found for " + completionNumber);
}
else
{
System.out.println("Found match: " + matched.toString());
}
}
}
NOTE:
Not sure you need the AthleteList class. It's just holding an ArrayList. If that's all that class will ever do then I suggest you just using an ArrayList. It will make your code cleaner.

Entering multiple things in to one array in java

I am quite new to java but have a project i need to complete and am stuck on a certain part.
I want to allow the user to enter a route including, start destination, an end destination, and a number of stops. I have been able to do this, but then i want the user to have the ability of being able to add the same things again, to the same array. without deleting the existing route
here is the code i have so far
import java.util.Scanner;
import java.util.Arrays;
public class main {
public static void main(String[] args){
menu();
}
public static void menu(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter 1 to input a new route");
int option = scanner.nextInt();
if(option==1){
inputRoute();
}
}
public static void inputRoute(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter Starting Destination");
String startDest = scanner.next();
System.out.println("Please Enter End Destination");
String endDest = scanner.next();
System.out.println("Please Enter Number of stops");
int numberOfStops = scanner.nextInt();
String[] stops = new String[numberOfStops];
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
stops[i-1] = scanner.next();
}
System.out.println(Arrays.toString(stops));
menu();
}
}
however when this runs, if i go back and enter in another route, it will just delete the existing route.
Is there any way of appending the next route to the end of that array or any way of doing this?
thank you
Like crush said. Rather than use a normal array of strings, use an ArrayList<String> object. Or even an ArrayList<String[]> and stash each individual route in there.
First of all you will need to declare the stops array as an instance variable, otherwise you will always be creating a new array whenever you call the method inputRoute().
and then to preserve old entries i can think of two ways-->
--> modify the loop as below...
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
if(stops!=null) //without the if condition it will also append null in the start
stops[i-1]=stops[i-1]+", "+ scanner.next(); // you can you any separator
else
stops[i-1]=scanner.next();
}
--> or you can ArrayList or any other Collection that provides auto increment
Try declaring stops as a global variable. (right below the class line)
Also I would recommend using an ArrayList, List something on those lines
You can't use an array for this (without constantly re-allocating them) as Arrays are fixed in size once created.
Use an ArrayList though and you can add as many items as you like whenever you like.
The easy (and slightly wrong) solution would be to make your array a static array that is defined outside any method. That will get you going (although you will have to make the array big enought.
Other recommendations:
Capatilize your Main class--avoids confusiong (even moreso if you
don't call it main!)
Make your public static void main method do
this: new Main()
Then get rid of all the other statics.
Use a collection instead of an array.
instead of adding each entry into the array separately (which will make EVERYTHING harder for you), create a second class with 3 fields (start, end, stop) and each time you input another record, "new" an instance of the second class, place the three things into the new instance and place that instance on your collection.
It may seem arbitrary and unnecessary right at this minute, but if you have ANY follow-on work to do on this class these things will make your life easier. If any seems confusing or you want to understand why, feel free to ask in the comments.
I think this will help you.
Main file.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
menu();
}
public static void menu(){
List<Route> routeList = new ArrayList<Route>();
Scanner scanner = new Scanner(System.in);
System.out.println("enter 1 to input a new route");
int option = scanner.nextInt();
if(option==1){
routeList.add(inputRoute());
}
System.out.println("Complete list of routes is "+routeList);
}
public static Route inputRoute(){
Route route = new Route();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the name of the route");
String name = scanner.next();
route.setName(name);
System.out.println("Please Enter Starting Destination");
String startDest = scanner.next();
route.setStartLocation(startDest);
System.out.println("Please Enter End Destination");
String endDest = scanner.next();
route.setEndLocation(endDest);
System.out.println("Please Enter Number of stops");
int numberOfStops = scanner.nextInt();
if(numberOfStops > 0){
route.setStopList(new ArrayList<String>());
for(int i = 1; i<=numberOfStops; i++){
System.out.println("Enter Stop" + i);
route.getStopList().add(scanner.next());
}
System.out.println("current entered route is "+route);
menu();
}
return route;
}
}
Route file:
import java.util.List;
public class Route {
String name ;
String startLocation;
String endLocation;
List<String> stopList;
public Route() {
}
public Route(String name, String startLocation, String endLocation, List<String> stopList) {
this.name = name;
this.startLocation = startLocation;
this.endLocation = endLocation;
this.stopList = stopList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartLocation() {
return startLocation;
}
public void setStartLocation(String startLocation) {
this.startLocation = startLocation;
}
public String getEndLocation() {
return endLocation;
}
public void setEndLocation(String endLocation) {
this.endLocation = endLocation;
}
public List<String> getStopList() {
return stopList;
}
public void setStopList(List<String> stopList) {
this.stopList = stopList;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Route route = (Route) o;
if (endLocation != null ? !endLocation.equals(route.endLocation) : route.endLocation != null) return false;
if (name != null ? !name.equals(route.name) : route.name != null) return false;
if (startLocation != null ? !startLocation.equals(route.startLocation) : route.startLocation != null)
return false;
if (stopList != null ? !stopList.equals(route.stopList) : route.stopList != null) return false;
return true;
}
#Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (startLocation != null ? startLocation.hashCode() : 0);
result = 31 * result + (endLocation != null ? endLocation.hashCode() : 0);
result = 31 * result + (stopList != null ? stopList.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Route{" +
"name='" + name + '\'' +
", startLocation='" + startLocation + '\'' +
", endLocation='" + endLocation + '\'' +
", stopList=" + stopList +
'}';
}
}

Trying to modify a game so that the program keeps a list of unaccepted answers and prints them at the end. (java)

I'm trying to write a program a picnic game that keeps a list of all the items that were rejected (but only one occurrence of each|if the user enters an item twice and it is rejected both times, it should appear only once in the list of rejected items). At the end of the game, prints out all the rejected items and the number of times the user's answer was rejected. I'm supposed to use an array list. what should I do? here's what I have so far.
import java.util.*;
public class PlayPicnic
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Picnic picnic = new Picnic();
while (picnic.numberOfItems() < 5)
{
System.out.print("What do you want to bring on the picnic? ");
String item = scan.nextLine();
if (picnic.okayToBring(item))
{
picnic.add(item);
}
else
{
System.out.println("Sorry, you can't bring " + item);
}
}
System.out.println("\nHere's what we'll have at the picnic:");
picnic.show();
}
}
and heres the corresponding picnic class
import java.util.*;
public class Picnic
{
// INSTANCE VARIABLES:
private ArrayList<String> stuffToBring; // items to bring on the picnic
// CONSTRUCTOR:
//-----------------------------------------------------
// Construct a new Picnic.
//-----------------------------------------------------
public Picnic()
{
stuffToBring = new ArrayList<String>(); // initialize list
}
//-----------------------------------------------------
// Given an item s, see if it's okay to add it to the list.
// Return true if it is, false otherwise:
//-----------------------------------------------------
public boolean okayToBring(String s)
{
// "Secret rule" -- s can't be an item already in the list:
if (stuffToBring.contains(s)) // "contains" is in the ArrayList class
{
return false;
}
else
{
return true;
}
}
//-----------------------------------------------------
// Given an item s, add it to the list (if it's okay to add it)
//-----------------------------------------------------
public void add(String s)
{
if (okayToBring(s))
{
stuffToBring.add(s);
}
}
//-----------------------------------------------------
// Print the items in the list
//-----------------------------------------------------
public void show()
{
for (int i = 0; i < stuffToBring.size(); i++)
{
String s = stuffToBring.get(i);
System.out.println(s);
}
// ALTERNATE APPROACH USING A "for next" LOOP:
// for (String s: stuffToBring)
// {
// System.out.println(s);
// }
}
//-----------------------------------------------------
// Returns the number of items in the list:
//-----------------------------------------------------
public int numberOfItems()
{
return stuffToBring.size();
}
}
I'm not sure that I understood your question, but it seems quite easy: add an ArrayList<String> and insert the item in the else inside the while. Then, after picnic.show(), you just print the ArrayList.
Here's the code:
Scanner scan = new Scanner(System.in);
Picnic picnic = new Picnic();
ArrayList<String> unaccepted = new ArrayList<>();
while (picnic.numberOfItems() < 5)
{
System.out.print("What do you want to bring on the picnic? ");
String item = scan.nextLine();
if (picnic.okayToBring(item))
{
picnic.add(item);
}
else
{
if(!unaccepted.contains(item)) unaccepted.add(item);
System.out.println("Sorry, you can't bring " + item);
}
}
System.out.println("\nHere's what we'll have at the picnic:");
picnic.show();
System.out.println(Arrays.toString(unaccepted.toArray()));
Create an array list
ArrayList<String> rejectedItems = new ArrayList<String>();
When you reject an offer
System.out.println("Sorry, you can't bring " + item);
You add the item to the list of rejected items
System.out.println("Sorry, you can't bring " + item);
rejectedItems.add(item);
If you NEED to use an ArrayList, at this point you would also need to run through the list and make sure the item you're adding isn't already there as ArrayLists allow duplicates.
At the end, you print them all out
for (String item : rejectedItems)
{
System.out.println("Rejected " + item);
}
You can use another ArrayList to keep track of unaccepted items.
As you are not adding duplicated items to unaccepted ArrayList you should also keep track of the number of wrong answers.
Here is a very basic solution:
import java.util.ArrayList;
import java.util.Scanner;
public class PlayPicnic {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Picnic picnic = new Picnic();
ArrayList<String> unaccepted = new ArrayList<String>();
int wrongAttempts = 0;
while (picnic.numberOfItems() < 5) {
System.out.print("What do you want to bring on the picnic? ");
String item = scan.nextLine();
if (picnic.okayToBring(item)) {
picnic.add(item);
} else {
wrongAttempts++;
if (!unaccepted.contains(item)) {
unaccepted.add(item);
}
System.out.println("Sorry, you can't bring " + item);
}
}
System.out.println("\nHere's what we'll have at the picnic:");
picnic.show();
System.out.println("Unaccepted items");
for (String item : unaccepted) {
System.out.println(item);
}
System.out.println("Your answer was rejected " + wrongAttempts + " times");
}
}

Categories