Stack and Array List - java

My assignment is to write a test program that prompts a user for 5 strings and displays them in reverse order using MyStack and ArrayList. I need help figuring out how to take user input and put it into the stack and print it in reverse.
MyStack Class
MyMain
My Main:
package arraylist;
import java.util.Scanner;
/**
*
* #author dghelardini
*/
public class ArrayList {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner userIn = new Scanner(System.in);
System.out.print("Enter five names: ");
}
}
MyStack Class:
package arraylist;
/**
*
* #author dghelardini
*/
public class MyStack extends ArrayList
{
private ArrayList<Object> theList = new ArrayList<>();
public boolean isEmpty()
{
return theList.isEmpty();
}
public int getSize()
{
return theList.size();
}
public Object peek()
{
return theList.get(getSize()-1);
}
public Object pop()
{
Object o = theList.get(getSize()-1);
theList.remove(getSize()-1);
return o;
}
public void push(Object o)
{
theList.add(o);
}
#Override
public String toString()
{
return "stack:" + theList.toString();
}
}

Scanner:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html?is-external=true
The user enters the string, then you call the stack to store the 5 strings. Then when you pop, the stack returns the last item that

Related

How is the for loop iterating to the next item in below code

I'm trying to learn the Iterator design pattern in Java. Below is a code sample of the implementation of the iterator pattern.
public class IteratorDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NameRepository repo=new NameRepository();
for(Iterator iter=repo.getIterarter(); iter.hasNext();){
String name=(String) iter.next();
System.out.println("Name : "+name);
}
}
}
interface Container{
public Iterator getIterarter();
}
interface Iterator{
public boolean hasNext();
public Object next();
}
class NameRepository implements Container{
private String[] names={"A","B","C","D","E","F"};
#Override
public Iterator getIterarter() {
return new NameIterator();
}
private class NameIterator implements Iterator{
int index;
#Override
public boolean hasNext() {
return index < names.length;
}
#Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
}
}
Here the output is A , B, C, D,E ,F. My question is how this for loop iterates to the next item ? As it seems there is no iterating value in the code, but still it prints out the whole array
See, index is increasing every time if index < names.length
**
#Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
**

An ArrayList contains two elements, how to return only the String element?

I'm pretty new to Java but I feel like this is an easy task. This arraylist has two elements...names and scores. I want to write a method that prints a list of all the names in the list, not the scores. I know I've done this before I just can't remember how lol
import java.util.ArrayList;
/**
* Print test scrose and student names as well as he average for the class.
*/
public class TestScores {
private ArrayList<Classroom> scores;
public int studentScores;
/**
* Create a new ArrayList of scores and add some scores
*/
public TestScores() {
scores = new ArrayList<Classroom>();
}
/**
* Add a new student and a new score.
*/
public void add (String name, int score) {
scores.add(new Classroom(name, score));
if(score > 100){
System.out.println("The score cannot be more than 100");
}
}
/**
* Return all the student names.
*/
public void printAllNames() {//this is the method.
for (Classroom s : scores){
System.out.println(scores.get(name));
}
}
}
and the classroom class:
import java.util.ArrayList;
/**
* This class creates the names and scores of the students
*/
public class Classroom {
public int score;
public String name;
/**
* Constructor for the Class that adds a name and a score.
*/
public Classroom(String aName, int aScore) {
score = aScore;
name = aName;
}
/**
* Return the name of the students
*/
public String returnName() {
return name;
}
/**
* Return he scores
*/
public int returnScore() {
return score;
}
}
public void printAllNames() {//this is the method.
for (Classroom s : scores){
System.out.println(s.returnName());
}
}
You should be precice in your question, your list does not contain 2 elements - names and scores - but multiple Classroom objects which contain names and scores.
Alternative answer using Java 8 streams:
scores.stream().map(c -> c.returnName()).forEach(System.out::println);

addFirst() in java.util.LinkedList

This is for homework.
I am making a stack using a linked list. I have chosen to use the linked list from Java's java.util.LinkedList package. When I call the addFirst() method in my Main class, the program won't finish. It acts like an infinite loop, but as far as I know there are no loops involved. Here is the code:
package assignment3;
import java.util.LinkedList;
/**
*
* #author Eric
*/
public class LinkedListStack<T> {
LinkedList linkedList = new LinkedList();
public boolean isEmpty() {
if (linkedList.isEmpty()) {
return true;
} else {
return false;
}
}
public int size() {
int size = linkedList.size();
System.out.println("The size of the stack is " + size);
return size;
}
// This is the problem method.
public void push(T element) {
linkedList.addFirst(element);
}
public void pop() {
while(!linkedList.isEmpty()){
linkedList.removeFirst();
}
}
public void peek() {
while(!linkedList.isEmpty()){
linkedList.peek();
}
System.out.println("The first element in the stack is " + linkedList.peek());
}
}
This is the class Main that calls the push() method.
package assignment3;
/**
*
* #author Eric
*/
public class Main {
public static void main(String args[]) {
LinkedListStack linkedListStack = new LinkedListStack();
linkedListStack.push(1); // This never finishes.
linkedListStack.peek();
linkedListStack.size();
}
}
It's very hard to test LinkedListStack.java because I cannot push anything onto the stack. I have no idea what's wrong.
while(!linkedList.isEmpty()){
linkedList.peek();
}
peek() will never change a linked list from nonempty to empty, since it doesn't change the list.
but as far as I know there are no loops involved
What do you think while is?

Making a Stack Method in Java

Is there any simple way to get the stack to display then empty itself inside the method "PrintAndEmpty"? I need the print and empty inside the method PrintAndEmpty and not the main. The codes are:
import java.util.*;
class Stack<E> implements StackInterface<E> {
private ArrayList<E> items;
public Stack() { // default constructor; creates an empty stack
items = new ArrayList<E>(); // initial capacity is 10
}
public Stack(int initialCapacity) {
//one argument constructor, creates a stack with initial capacity initialCapacity
items = new ArrayList<E>(initialCapacity);
}
public void push(E x) {
items.add(x); //uses the ArrayList method add(E o)
}
public E pop() {
if (empty()) // determine whether or not there is an item to remove
return null;
return items.remove(items.size()-1); //uses the ArrayList method remove(int n)
}
public boolean empty() {
return items.isEmpty();//uses the ArrayList method isEmpty()
}
public int size() {
return items.size(); //uses the ArayList method size()
}
public E peek() {
if (empty()) // determine whether or not there is an item on the stack
return null;
return items.get(items.size()-1); //uses the ArrayList method get(int i)
}
public void PrintAndEmpty()
{
// I want to print then empty the stack here, not in the main method.
}
Main method
public static void main (String[] args) // for demonstration only
{
Stack<Student> s = new Stack<Student>();
// push five Student references onto s
s.push(new Student("Spanky", "1245"));
s.push(new Student("Alfalfa", "1656"));
s.push(new Student("Darla", " 6525"));
s.push(new Student("Stimie", "1235"));
s.push(new Student("Jackie", "3498"));
// The data below is what I am trying to put in the PrintAndEmpty method
while(!s.empty())
System.out.println(s.pop().getName());
System.out.println();
System.out.println("The size of the stack is now "+s.size());
}
The Student Class for testing purposes:
public class Student
{
private String name;
private String id;
public Student()
{
name = "";
id = "";
}
public Student (String n, String idNum)
{
name = n;
id = idNum;
}
public String getName()
{
return name;
}
public String getID()
{
return id;
}
public void setName(String n)
{
name = n;
}
public void setID( String idNum)
{
id = idNum;
}
public boolean equals(Object o) // name and id are the same
{
return ( (((Student)o).name).equals(name) &&
(((Student)o).id).equals(id) );
}
}
I am all out of ideas as far as getting this to work. If anyone has suggestions, please let me know. I would greatly appreciate it!
Not sure why you'd want to do that, but here is how you would do it:
// PrintAndEmpty 'this' stack.
public void PrintAndEmpty()
{
// The condition to check - e.g. 'this' stack.
while(!this.empty()) {
// Pop from the stack - e.g. 'this' stack.
System.out.println(this.pop().getName());
}
}

Create several new objects within a for-loop in Java

I want to create several objects from a class in a for loop. but I don't know how to code it. What I have written creates a new object but it overwrites the previous object.
package assginment1_version4;
import java.util.*;
public class Client {
public static void main (String[] args) {
System.out.println ("this is a bill database");
System.out.println ("add a user?(Y/N)");
Scanner input = new Scanner(System.in);
String answer = input.nextLine ();
ArrayList ary = new ArrayList ();
for (int i=1 ; i < 100; i++) {
if (answer.equalsIgnoreCase("y")) {
Bill bill1 = new Bill();
System.out.println("user first name:");
bill1.setFname (input.nextLine());
System.out.println("user Last name:");
bill1.setLname (input.nextLine());
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
} else if (answer.equalsIgnoreCase ("n")) {
if (Bill.getBillCounter () == 0) {
System.out.println ("the Database is empty");
break;
} else {
System.out.println ("Number of Users: "
+ Bill.getBillCounter ());
break;
}
} else {
while (!answer.equalsIgnoreCase ("n")
&& !answer.equalsIgnoreCase ("y")) {
System.out.println ("add a user?(Y/N)");
answer = input.nextLine ();
}
}
}
}
}
please help me to complete this code.
You're overriding them because you create a new Bill on each loop and never save them off anywhere. I believe you want to add them to your ArrayList:
First, you should add a type to your ArrayList:
ArrayList<Bill> ary = new ArrayList<Bill>();
Then, before you get the input from the user on whether or not to add a new Bill, you should add the current one to this list:
...
System.out.println("user Last name:");
bill1.setLname(input.nextLine());
ary.add(bill1);
...
You haven't used the ArrayList, you need to add the Bill's objects at the end of the for loop.
ary.add(bill1);
and add a type to your ArrayList
ArrayList<Bill> ary = new ArrayList<Bill>();
This is the Bill class.....
package assginment1_version2;
public class Bill {
/**
* Attributes of a bill
*/
private String firstName;
private String lastName;
private int paymentDeadline;
private int paymentCode;
private int billCode;
/**
* Attribute of Bill Class
*/
private static int BillCounter=0;
/**
* Methods of Bill class
* #return number of users
*/
/*public static int getBillCounter(){
return BillCounter;
}*/
/**
* Class Constructor
* #param Fname is the first name of user
* #param Lname is the last name of user
* #param Pdeadline is the deadline of paying the bill
* #param Pcode introduces the payment uniquely
* #param Bcode introduces the bill uniquely
*/
public Bill (){
BillCounter++;
}
/**
* FirstName methods
* method to set FirstName
* #param n is the input of setname method as a user name
*/
public void setFname (String n){
firstName=n;
}
// method to get FirstName
public String getFname (){
return firstName;
}
/**
* LastName methods
* method to set LastName
*/
public void setLname (String m){
lastName=m;
}
// method to get LastName
public String getLname(){
return lastName;
}
/**
* PaymentDeadline methods
* method to set PaymentDeadline
*/
public void setPaymentDeadline(int m){
paymentDeadline= m;
}
//method to get PaymentDeadline
public int getPaymentDeadline(){
return paymentDeadline;
}
/*
* PaymentCode methods
* Method to set PaymentCode
*/
public void setPaymentCode (int m){
paymentCode=m;
}
//method to get PaymentCode
public int getPaymentCode(){
return paymentCode;
}
/*
* Methods of BillCode
* method to set BillCode
*/
public void setBcode(int Bcode){
billCode=Bcode;
}
//method to get BillCode
public int getBcode(){
return billCode;
}
}

Categories

Resources