Change element in arraylist to true from user input - java

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;

Related

Setter which has class instance is this possible?

private int Li_WtVal;
List <Integer> ValueList = new ArrayList<Integer>();
CsReader csReader = new CsReader();
public void setLi_WtVal(int li_WtVal) {
ValueList = csReader.GetAllcsValues();
li_WtVal = ValueList.get(0);
}
public int getLi_WtVal() {
return Li_WtVal;
}
}
And I have a while loop inside it I'm calling the setter and getter but evrytime It returns 0.
public int CtrlWeight(String CodeLine) {
Scanner scanner = new Scanner(CodeLine);
int Li_Wtcs = 0;
while (scanner.hasNext()) {
token1 = scanner.next();
if (token1.contains("if")){
setLi_WtVal(Li_WtVal);
Li_Wtcs = Li_Wtcs + getLi_WtVal() ;
}
}
Can setter has other class instances and object ref inside it?
You set the value to the parameter not to the property:
public void setLi_WtVal(int li_WtVal) {
ValueList = csReader.GetAllcsValues();
Li_WtVal= ValueList.get(0);
}
public int getLi_WtVal() {
return Li_WtVal;
I think the reason is because your teriable naming of the variables.
Also Looks like your code doesn't make much.

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;
}
}

How do you use methods from sub classes in the main class in Java?

I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.

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

confused about Return Value

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.

Categories

Resources