confused about Return Value - java

I'm working on a project called MovieDatabase. For my methods searchTitle, searchGenre, searchDirector, and searchYear, the methods are supposed to take a substring and see if they can be found anywhere in the database. What I have now compiles but when I test the methods from the BlueJ project they return only null. What do I change to make them return the right things? Here is my code in its entirety (P.S. there's a separate class called MovieEntry that handles the get methods):
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<String> searchTitle(String substring){
for (MovieEntry m : Database)
if(m.getTitle().contains(substring)){
System.out.println(m.getTitle());
}
return null;
}
public ArrayList<String> searchGenre(String substring){
for (MovieEntry m : Database)
if(m.getGenre().contains(substring)){
System.out.println(m.getGenre());
}
return null;
}
public ArrayList<String> searchDirector (String substring){
for (MovieEntry m : Database)
if(m.getDirector().contains(substring)){
System.out.println(m.getDirector());
}
return null;
}
public ArrayList<MovieEntry> searchYear(int year){
ArrayList<MovieEntry> yearMatches = new ArrayList<MovieEntry>();
for (MovieEntry m : Database) {
if (m.getYear() == year) {
yearMatches.add(m);
}
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <MovieEntry> Matches = new ArrayList<MovieEntry>();
for(MovieEntry m : Database){
if(m.getYear() >= from && m.getYear() <= to){
Matches.add(m);
}
}
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File("movies"));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
ArrayList <String> gList = new ArrayList<String>();
for(MovieEntry m : Database){
String g = m.getGenre();
if(gList.contains(g) == false){
gList.add(g);
}
}
return gList.size();
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector();
if(dList.contains(d) == false){
dList.add(d);
}
}
return dList.size();
}
// public String listGenres(){
// ArrayList <String> genreList = new ArrayList<String>();
// return genreList;
// }
}

You must modify methods of the following nature
public ArrayList<String> search*(String substring){
Remove System.out.println. Instead, add match to a new array list of strings.
public ArrayList<String> searchTitle(String substring){
ArrayList<String> matches = new ArrayList<String>();
for (MovieEntry m : Database)
if(m.getTitle().contains(substring)){
matches.add(m.getTitle());
}
return matches;
}
Wherever you are calling the searchTitle(), check resulting arraylist for isEmpty() to make sure that the result is not empty.

Related

Letter Combinations of a Phone Number Everything is correct except 1 test where input is just ""

I have returned an empty String but the desired output shows I should return nothing.
How can I return nothing?
Pls, refer to the attached image, you'll understand the question.
Below I am adding my code pls tell me which part I can improve-
import java.util.*;
class Solution {
public List<String> letterCombinations(String digits) {
String mapping[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int num=0;
try{
num=Integer.parseInt(digits);
} catch(NumberFormatException ex){ // handle your exception
System.out.print("error");
}
List<String> ans=new ArrayList<>();
// List<String> res=new ArrayList<>();
ans = helper(num,mapping);
return ans;
}
public List<String> helper(int num, String mapping[]){
if(num<=0){
List<String> ans=new ArrayList<>();
ans.add("");
return ans;
}
List<String> smallAns=new ArrayList<>();
int myNum=num%10;
smallAns=helper(num/10, mapping);
String s=mapping[myNum];
List<String> ans=new ArrayList<>();
ans=appendStr(s, smallAns);
return ans;
}
public List<String> appendStr(String s, List<String> res){
List<String> out=new ArrayList<>();
int l=s.length();
int i=0;
while(i<l){
for(int j=0;j<res.size();j++){
String toAdd=res.get(j)+s.charAt(i);
out.add(toAdd);
}
i++;
}
return out;
}
}
Added this block of code now it's working
if(digits.length()==0){
List<String> ans=new ArrayList<>();
return ans;
}
The above block of code is added letterCombinations function which will return empty array list if the String provided by user is empty as required.
import java.util.*;
class Solution {
public List<String> letterCombinations(String digits) {
if(digits.length()==0){
List<String> ans=new ArrayList<>();
return ans;
}
String mapping[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int num=0;
try{
num=Integer.parseInt(digits);
} catch(NumberFormatException ex){
System.out.print("error");
}
List<String> ans=new ArrayList<>();
ans = helper(num,mapping);
return ans;
}
public List<String> helper(int num, String mapping[]){
if(num<=0){
List<String> ans=new ArrayList<>();
ans.add("");
return ans;
}
List<String> smallAns=new ArrayList<>();
int myNum=num%10;
smallAns=helper(num/10, mapping);
String s=mapping[myNum];
List<String> ans=new ArrayList<>();
ans=appendStr(s, smallAns);
return ans;
}
public List<String> appendStr(String s, List<String> res){
List<String> out=new ArrayList<>();
int l=s.length();
int i=0;
while(i<l){
for(int j=0;j<res.size();j++){
String toAdd=res.get(j)+s.charAt(i);
out.add(toAdd);
}
i++;
}
return out;
}
}

To check List of String within a String

I have a List<String> and List<Object>. Where, in List<String> I have Strings that I want. In another List<Object>, One of the string variable will have all the Strings that I want. How can I get that String or How can I return true when I found all the listOne Strings.
Example:
List<String> listOne = ["I have"," three"," Dollars"]
List<Object> listTwo = [[1,"I have One Dollar", 500],
[2,"I have two Dollars", 541],
[31,"I have three Dollars with card", 568]
[3,"I have three Dollars", 568],
[4,"I have Four Dollars", 521]]
How I can get Fourth object from listTwo when my listOne Strings exactly matched.
Code Part:
Details.java:
public class Details {
int sNo;
String text;
int value;
public int getsNo() {
return sNo;
}
public void setsNo(int sNo) {
this.sNo = sNo;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Main Class:
package com.adp.aca.core.helper.daoimpl;
import java.util.ArrayList;
import java.util.List;
import org.apache.velocity.runtime.directive.Foreach;
public class TestClass {
static int count ;
public static void main(String args[]) {
List<String> listOne = new ArrayList<String>();
listOne.add("I have");
listOne.add(" three");
listOne.add(" Dollars");
List<Details> listTwo = new ArrayList<Details>();
Details detailOne = new Details();
detailOne.setsNo(1);
detailOne.setText("I have One Dollar");
detailOne.setValue(500);
Details detailTwo = new Details();
detailTwo.setsNo(2);
detailTwo.setText("I have two Dollars");
detailTwo.setValue(541);
Details detailThree = new Details();
detailThree.setsNo(31);
detailThree.setText("I have three Dollars with card");
detailThree.setValue(568);
Details detailFour = new Details();
detailFour.setsNo(3);
detailFour.setText("I have three Dollars");
detailFour.setValue(568);
Details detailFive = new Details();
detailFive.setsNo(4);
detailFive.setText("I have Four Dollars");
detailFive.setValue(521);
listTwo.add(detailOne);
listTwo.add(detailThree);
listTwo.add(detailFour);
listTwo.add(detailFive);
listTwo.add(detailTwo);
List<String> actualStrings = new ArrayList<String>();
for (Details detail : listTwo) {
actualStrings.add(detail.getText());
}
/** Ended up here ***/
for (int i = 0; i < actualStrings.size(); i++) {
for (int j=0; j<listOne.size();j++) {
actualStrings.get(i).contains(listOne.get(j));
count=i;
}
}
}
}
static String concat(List<String> l) {
StringBuilder sb = new StringBuilder();
for(String s : l)
sb.append(s);
return sb.toString();
}
static Details getMatch(List<Details> listTwo, String s) {
for (Details d : listTwo) {
if (d.getText().equals(s))
return d;
}
return null;
}
You can use the functions like this:
Detail d = getMatch(listTwo, concat(listOne));
you can build a String from List one and compare with Object list in a loop or you can iterate through 2 list and compare as shown in the pseudo code.
for (Details detail: listTwo) {
String text = detail.getText();
String[] texts = text.split(" ");
List textList = Arrays.asList(texts);
if (texts.length == listOne.size()) {
int count = 0;
for (String val: listOne) {
if (textList.contains(val) count++;
else break;
}
if (count == listOne.size()) {
result = detail;
}
}
else {
break;
}
}

Change element in arraylist to true from user input

package issue;
import java.util.*;
public class Issue {
private static ArrayList<Object> list = new ArrayList<Object>();
public static ArrayList<Object> getArrayStringList(){
for (Object o : list)
System.out.println("["+o+"]");
return list;
}
public static void removeIssue(){
for (int i = 0; i<list.size(); i++){;
System.out.println("["+"["+i+"] "+list.get(i)+"]");
}
Scanner scan = new Scanner(System.in);
System.out.println("Which one would you like to mark as solved?");
int choice = scan.nextInt();
##This is where my problem is ##
Object issue = list.get(choice);
issue
}
public static void addIssue(){
Scanner scan = new Scanner(System.in);
String text= scan.nextLine();
newIssue issue = new newIssue(text);
list.add(issue);
}
}
I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to
package issue;
public class newIssue {
public String issueText;
public boolean returned = false;
public newIssue(String issueText){
this.issueText = issueText;
}
public String toString(){
return issueText + returned;
}
}
Try this.
if(list.size() > 0 && choice <= list.size()-1) {
newIssue issue = (newIssue)list.get(choice);
issue.returned = true;
System.out.println("newIssue = "+ issue.toString())
}
Create list as:
private static ArrayList<newIssue> list = new ArrayList<>();
Then you can do:
newIssue issue = list.get(choice);
issue.returned = true;

Convert Linkedlist to ArrayList

I had to write a program to do LZWDecode and I decided to use LinkedList to write the LZWDecode program below but I want to convert it to an ArrayList. Anyone have idea on how I can convert the LinkedList to an ArrayList to make it simpler.
Thanks.
import java.util.*;
public class LZWDecoder {
private final int CLEAR_TABLE=256;
private final int END_OF_DATA=257;
private final int TABLE_SIZE=4096;
private static LinkedList<Integer> input = new LinkedList<Integer>();
#SuppressWarnings("unchecked")
private LinkedList<Integer>[] table
= new LinkedList[TABLE_SIZE];
private LinkedList<Integer> temp = new LinkedList<Integer>();
private int index = 258;
private LinkedList<String> trace = new LinkedList<String>();
private boolean view = true;
private void enterData() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Input Code (EOD = 257):");
int n=0;
while(n!=END_OF_DATA && scan.hasNextInt()){
n = scan.nextInt();
//System.out.println("Adding "+n);
input.add(n);
}
System.out.println("Decoding...\nOutput:");
String code="";
for(int i=0; i<input.size(); i++) {
code+=input.get(i)+" ";
}
trace.add("\nInput: "+code);
//test
/*
while(!input.isEmpty()) {
System.out.println(input.remove());
}
*/
}
private void reset() {
trace.add("Clearing...");
//table.clear();
for(int i=0; i<TABLE_SIZE;i++) {
table[i] = new LinkedList<Integer>();
}
}
private void decode(int c) {
switch(c) {
case CLEAR_TABLE:
trace.add("decode\t"+CLEAR_TABLE+"->[256]");
reset();
break;
case END_OF_DATA:
trace.add("decode\t"+END_OF_DATA+"->[257]");
trace.add("Decoding finished.");
break;
default:
if(c<256) {
trace.add("decode\t"+c+"->["+c+"]");
if(!temp.isEmpty()) append(c);
emit(c);
add(temp);
} else {
trace.add("decode\t"+c+"->["+printTableNode(table[c])+"]");
if(!temp.isEmpty()) append(table[c].get(0));
emit(c, table[c]);
add(temp);
}
}
}
private void emit(int n, LinkedList<Integer> c) {
//int [] a=new int[c.size()];
temp=new LinkedList<Integer>();
for(int i=0; i<c.size(); i++) {
//a[i]=c.get(i);
System.out.print(c.get(i)+" ");
temp.add(c.get(i));
}
trace.add("emit\t"+n+"->"+"["+printTableNode(c)+"]");
}
private void emit(int c) {
//print out output
temp=new LinkedList<Integer>();
temp.add(c);
trace.add("emit\t"+c+"->"+"["+c+"]");
System.out.print(c+" ");
}
/*
private void add(int c) {
//added to table is copied to temp
table[index].add(c);
temp = (LinkedList)table[index].clone();
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
*/
private void add(LinkedList<Integer> c) {
for(int i=0; i<c.size();i++) {
//temp.add(c.get(i));
table[index].add(c.get(i));
}
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
private void append(int c) {
//table[c].add(12);//add what?
//temp.add(c);
table[index].add(c);
trace.add("append\t"+index+"->["+printTableNode(table[index])+"]");
index++;
}
private String printTableNode(LinkedList l) {
String list="";
for(int i=0; i<l.size();i++) {
list+=l.get(i);
if(i<l.size()-1) {
list+=", ";
}
}
return list;
}
private void printTrace() {
System.out.print("Printing Trace...");
for(int i=0; i<trace.size(); i++) {
System.out.println(trace.get(i));
}
}
public static void main(String[] args) {
// TODO code application logic here
LZWDecoder d = new LZWDecoder();
d.enterData();
while(!input.isEmpty()) {
d.decode(input.remove());
}
System.out.print("\n\n");
d.printTrace();
}
}
LinkedList<String> ll= new LinkedList<String>();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
List<String> myAL = new ArrayList<String>(ll);
for (Object alObject : myAL)
System.out.println(alObject);
So as you can easily convert the LinkedList to ArrayList bu using its constructor with passing Collection in it.
Hope it will clear your doubt.
Question is not clear enough.
Do you want to use ArrayList instead of Linked List?
Or do you want to convert a Linked List to an ArrayList?
First of all please declare variables on their interface not on implementation,
i.e
LinkedList<Integer>[] table = new LinkedList[TABLE_SIZE];
Instead use
List<Integer>[] table = new LinkedList[TABLE_SIZE];
Please provide a little more details on what you really looking for ....
If you want an array List from another collection, do this,
List<T> t = new ArrayList<>();
t.addAll(linkedList);
Regards
Lyju

Java Question Linked List objects

I have the following piece of code :
Essentially the number of methods should remain the same as in the code and I need to extract a string from an element of the linkedlist of Objects of type emp_struct.. How do I do it?
import java.util.*;
import java.io.*;
class a1 {
static LinkedList l1;
private emp_struct input() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
emp_struct obj = new emp_struct();
obj.emp_id = br.readLine();
obj.name = br.readLine();
obj.salary = Double.parseDouble(br.readLine());
obj.dept = br.readLine();
try{
search(obj);
}catch(Exception e){
System.out.println(e);
obj = input();
}
return obj;
}
boolean search(emp_struct obj)
{
int lastIndex = l1.lastIndexOf(l1);
int begIndex = 0;
for(begIndex =0;begIndex<lastIndex;begIndex++)
{
Object chkCase = l1.get(begIndex);
String chk = chkCase.getEmpID();
if(chk.equals(obj.emp_id));
throw new DuplicateEntryException("Duplicate entry found");
}
return true;
}
public static void main(String args[]) throws IOException
{
l1 = new LinkedList();
}
}
class DuplicateEntryException extends Exception {
String detail;
DuplicateEntryException(String a)
{
detail = a;
}
public String toString()
{
return "User Defined Exception : "+detail;
}
}
class emp_struct {
public String emp_id;
public String name;
public double salary;
public String dept;
public String getEmpID()
{
return emp_id;
}
public String toString()
{
return emp_id+"\t"+name+"\t"+salary+"\t"+dept;
}
}
In your search method, if you find the value, you're throwing an exception. If you don't find the value, you return true. This doesn't seem like the best approach.
If you find the value, shouldn't you return true, then if it makes it through the array without finding it, shouldn't you return false?
This line
Object chkCase = l1.get(begIndex);
should be
emp_struct chkCase = (emp_struct)l1.get(begIndex);
among other things...

Categories

Resources