So I am pretty stuck. I have some code that is being using inside my main method which needs to override the given methods and print out a statement. I got the statement in offer(E s) to work, but can't seem to get the statements in peek() and size() to print. They are functioning properly, but the statements "Peeking at list" and "Reporting list size" just won't print in their methods. If some people can shed some light it would be greatly appreciated! The main is located in a separate file
import java.io.*;
import java.util.*;
import java.awt.*; //for Point
public class StudentList<E>extends LinkedList<E> {
public boolean offer(E s) {
super.offer(s);
System.out.println("Offering "+ s);
return true;
}
public boolean contains(Object o) {
super.contains(o);
return false;
}
public E peek(E slist){
super.peek();
System.out.println("Peeking at list") ;
return slist;
}
public int size(Integer ilist){
System.out.println("Reporting list size");
size(ilist);
//System.out.println("Reporting list size");
return ilist;
}
}
Here is the main method:
public class OfferDriver
{
public static void main ( String[] args)
{
StudentList<Integer> ilist = new StudentList<Integer>( );
StudentList<String> slist = new StudentList<String>( );
String s;
Integer i;
Scanner in = new Scanner(System.in);
System.out.print("Please enter a word to offer (\"stop\" to stop):\t");
while (in.hasNext()) {
s = in.next();
if (s.equalsIgnoreCase("stop")) { break; }
slist.offer(s);
System.out.println("Size is: " + slist.size());
System.out.print("Please enter a word to offer (\"stop\" to stop):\t");
}
System.out.println("\n" + slist);
String si = slist.peek();
System.out.println("Testing peek(): " + si);
System.out.print("Please enter an integer to offer (<any word> to stop):\t");
while (in.hasNextInt()) {
i = in.nextInt();
ilist.offer(i);
System.out.println("Size is: " + ilist.size());
System.out.print("Please enter an integer to offer (<any word> to stop):\t");
}
System.out.println("\n" + ilist);
int pi = ilist.peek();
System.out.println("Testing peek(): " + pi);
}
}
}
Most likely your peek and size methods are not called. You can always check that with the help of a debugger. You seems to be wrongly overriding the methods. So try adding #override on top of your methods.
LinkedList peek method does not take any param but your method does:
public E peek(E slist)
so it means that you are not overriding the method.
peek() is not the same as peek(E) that you have implemented.
You have defined peek within your StduentList as
public E peek(E slist) {
But are using
String si = slist.peek();
To call it...
In fact, I'm having a hard time trying to figure out why you need to override any of the methods in the first place...
When you are calling the peek() and size() in main, you called this method from
String java.util.LinkedList.peek()
int java.util.LinkedList.size()
this are not your method, which you write in your StudentList Class.
Related
I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.
Im having difficulty understanding what exactly I should pass my third method in the main class with. Im really just sort of lost at this point. Any help would be awesome. Here is my code that I have written:
Also, here are the directions for boolean method called "getOrder":
Write a method called getOrder that takes an ArrayList of Strings as a parameter (the products ArrayList) and returns a boolean.
In the method body, prompt the user to enter a product name (a String), then check whether the product name exists in the ArrayList of strings.
If it exists, return true, otherwise return false.
public static void main(String[] args) {
// Call your methods here
bannerPrinter();
productBuilder();
getOrder(??); -----------------------------Confused as to what to pass this method with
}
// Write your methods below here
public static boolean getOrder(ArrayList<String> products) {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Please enter a product name: ");
String productName = in.nextLine();
if (products.contains(productName)) {
return true;
}
else {
return false;
}
}
public static ArrayList<String> productBuilder() {
ArrayList<String> products = new ArrayList<String>();
products.add("Desktop");
products.add("Phone");
products.add("TV");
products.add("Speaker");
products.add("Laptop");
return products;
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
}
You need to pass an ArrayList<String>. Looking at your code, you build one with productBuilder() which is otherwise unused. So:
ArrayList<String> products = productBuilder();
getOrder(products);
or
getOrder(productBuilder());
BTW, the following code:
if (products.contains(productName)) {
return true;
}
else {
return false;
}
is more easily written as
return products.contains(productName);
You would just pass an ArrayList. Like this:
ArrayList<String> lst = new ArrayList<String>();
lst.add("Phone");
lst.add("Laptop");
getOrder(lst);
You would fill your ArrayList first of course and then pass it.
I made a code which uses one input and store it in a genertic list and then I use another input to compare it with the first input ... If the first input is "Eric 1991" while the second input is just "Eric" so I want to print out all the sequence like this "Erik 1991" .. I used different ways to search in the namebirthday list , I used for loop then I used contains but they seeme do not work ,, Now I use toLowerCase().contains(x.toLowerCase()
I am getting error in eclipse in line of toLowerCase().contains(x.toLowerCase()
How can I correct that line to run the code???
package shapes;
import java.util.ArrayList;
import java.util.Scanner;
public class Base {
public static void main(String [] args) {
ArrayList<String> namebirthday = new ArrayList<String>();
Scanner sn = new Scanner(System.in);
String n=sn.nextLine();
// String k=sn.nextLine();
// String m=sn.nextLine();
namebirthday.add(n);
// namebirthday.add(k);
// namebirthday.add(m);
Scanner sb = new Scanner(System.in);
String x=sb.nextLine();
if (namebirthday.toLowerCase().contains(x.toLowerCase())){ // The method toLowerCase() is undefined for the type ArrayList<String>
System.out.println(namebirthday);
} else {
System.out.println("x" +"is not found" );
}
}
}
Acually I tried to put if (((String) namebirthday).toLowerCase().contains(x.toLowerCase())){ but eclipse says "Cannot cast from ArrayList to String- The method toLowerCase() is undefined for the type ArrayList"
What to do???
thanks
You have to use foreach to get the element form your lest and then do your comparison.
If you use namebirthday.contains then this will won't work for input is like "Eric".
See following code:
for(String currentString : namebirthday){
if (currentString.toLowerCase().contains(x.toLowerCase())){
System.out.println(currentString );
} else {
System.out.println("x" +"is not found" );
}
}
Cannot cast from ArrayList to String- The method toLowerCase() is
undefined for the type ArrayList
if (namebirthday.contains(x.toLowerCase())){
System.out.println(x);
} else {
System.out.println("x" +"is not found" );
}
}
You cannot use toLowerCase() in on a list. You have to implent yourself the contains method.
private static boolean containsIgnoreCase(List<String> nameBrithday, String s) {
for (String s1 : nameBrithday){
if ( s1.toLowerCase().contains(s.toLowerCase())){
return true;
}
}
return false;
}
You can't call toLowerCase() on the array, you have to call it on each of the members of the array:
boolean found = false;
for(String nm : namebirthday) {
if (nm.toLowerCase().contains(x.toLowerCase())) {
System.out.println(nm);
found = true;
// Add a break; here if you only care about the first match
}
}
if(!found) System.out.println("x" +"is not found" );
namebirthday is a List instance, not a String one. If you want to check something on content of this list, you need to get a single element that is a String. I am posting two examples how you can do it (the first one is probably more useful for you):
Check if the list contains the element
if (namebirthday.contains("Erik 1991")) {
// Do something
}
Iterate whole list and do the checking on each element
for (String element : namebirthday) {
if (element.equals("Erik 1991")) {
// Do something
}
}
Here is the fixed code
package shapes;
import java.util.ArrayList;
import java.util.Scanner;
public class Base {
public static void main(String [] args) {
ArrayList<String> namebirthday = new ArrayList<String>();
Scanner sn = new Scanner(System.in);
String n=sn.nextLine();
// String k=sn.nextLine();
// String m=sn.nextLine();
namebirthday.add(n);
// namebirthday.add(k);
// namebirthday.add(m);
Scanner sb = new Scanner(System.in);
String x=sb.nextLine();
for (String str : namebirthday){
if (str.toLowerCase().contains(x.toLowerCase())){
System.out.println(str);
} else {
System.out.println("x" +"is not found" );
}
}
}
}
I have been trying to solve this problem for ages and with no luck I didn't progress. Could someone please help me out. I have created an arrayList, made an getter class, have made a method. I can add stuff to the array list as well but when I print the arrayList out it prints out some random text.
below is the arrayList I created.
public static ArrayList<getArrayList> arrayList = new ArrayList<getArrayList>();
here is my method;
private static void addToArrayList(String a, double no1, int no2, int no3) {
try {
arrayList.add(new getArrayList(a, no1, no2, no3));
} catch (Exception e) {
e.printStackTrace();
}
}
here is my getter class
public class getArrayList {
private String name;
private double seconds;
private int speed1;
private int speed2;
public String getName() {
return name;
}
public double getSeconds() {
return seconds;
}
public int getSpeed1() {
return speed1;
}
public int getSpeed2() {
return Speed2;
}
public StoreCommands(String storeName, double storeSeconds, int storeSpeed1, int storeSpeed2) throws Exception{
name = storeName;
seconds = storeSeconds;
speed1 = storeSpeed1;
speed2 = storeSpeed2;
}
}
to add stuff on this list I use the method I created
addToArrayList(String a, double no1, int no2, int no3) filled in with my values
and to receive stuff from the arraylist I use this
for(getArrayList s : arrayList) {
System.out.println(arrayList + "\n")
;
and it prints out if i use System.out.println(arrayList), depending on how much I add to the arraylist.
[StoreCommands#49a21b63]
Besides that could someone tell me how I can set a size of the arrayList so if anything more that is being added it won't add and give an error.
Also I need to perform certain error checks once the items are in the arrayList
*1st If the an item is added to the list and the user tries to add the same one again straight after I want to display an error.. (the user can add the same stuff but not directly after the one they just added, they will need to add something else first)
*2nd if say user wants to add apples to the list, I want to limit that to only 2 time in the whole list, more than that will not be added and will display and error.
Could someone help me out please, I will really appreciate it.
Thanks.
Try this -
for(getArrayList s : arrayList)
System.out.println(s + "\n");//This print the tostring of getArrayList class
Again override the toString method of getArrayList class, to print actual field value of the object. Example -
public class getArrayList {
public String toString(){
return name +"||" +seconds+"||"+ speed1+"||"+speed2;
}
}
Note : Follow java nomenclature standard, first later of you class name would be capital And also give a relevent name to the Class.
Overriding toString method will help you to print actual data. Override it in your class getArrayList. One more thing is class name should start with capital letter.
public String toString()
{
return "Name : "+name+" Seconds : "+seconds+" Speed1 : "+speed1+" Speed2 : "+speed2;
}
and use it like
for(getArrayList s : arrayList)
System.out.println(s.toString);
You can limit the size by adding check to
private static void addToArrayList(String a, double no1, int no2, int no3) {
try
{
if(arrayList.size < 10) //any size you want
arrayList.add(new getArrayList(a, no1, no2, no3));
else
System.out.println("ArrayList is full");
} catch (Exception e) {
e.printStackTrace();
}
}
You don't have to loop in order to print an array, just do:
System.out.println(Arrays.toString(arrayList.toArray()));
ArrayList doesn't have a mechanism to limit the size, if you want to do it - you'll have to implement it.
Example:
import java.util.ArrayList;
/**
* User: alfasin
* Date: 2/5/14
*/
public class RestrictedSizeArrayList<E> extends ArrayList<E> {
private static final int limit = 6;//example
#Override
public boolean add(E e){
if(this.size() > 5){
throw new IndexOutOfBoundsException("Can't add more than 5 elements to the ArrayList");
}
boolean result = super.add(e);
return result;
}
}
I've been trying to create a method (in a separate class) that takes a String as a parameter and uses a premade SoundEngine (a different class) object to play that file inputted as a string. This is the code I have so far. The problem comes up with
SoundEngine.playCompletely(file);
import java.util.ArrayList;
public class AudioFileList
{
// Field for a quantity of notes.
private ArrayList<String> files;
// Constructor that initializes the array field.
public AudioFileList()
{
files = new ArrayList<String>();
}
// Method to add file names to the collection.
public void addFile(String file)
{
files.add(file);
}
// Method to return number of files in the collection.
public int getNumberOfFiles()
{
return files.size();
}
// Method to print the strings in the collection.
public void listFiles()
{
int index = 0;
while(index < files.size())
{
System.out.println( index + ":" + files.get(index));
index++;
}
}
// Method that removes an item from the collection.
public void removeFile(int fileNumber)
{
if(fileNumber < 0)
{
System.out.println ("This is not a valid file number");
}
else if(fileNumber < getNumberOfFiles())
{
files.remove(fileNumber);
}
else
{
System.out.println ("This is not a valid file number");
}
}
// Method that causes the files in the collection to be played.
public void playFile(String file)
{
SoundEngine.playCompletely(file);
}
}
Any help is very much appreciated.
SoundEngine's playCompletely function is an instance function, not a class function. So instead of:
SoundEngine.playCompletely(file); // Compilation error
you want:
// First, create an instance of SoundEngine
SoundEngine se = new SoundEngine();
// Then use that instance's `playCompletely` function
se.playCompletely(file);