Java Constructor by String parameters [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello my problem is that
DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= new String(v[0]);
interes= new List(v[1]);
}
This constructor is for be able to build and object by a file and I want transform the element v[1] in List(interes).
Thanks for your help guys.

You don't need to create a String with new String("") you can just set banco = v[0]
List is an Interface and can not be instantiated via a constructor. What you need is a ArrayList for example. But this class doesn't have a Constructor for a Strign neither. What is in that String v[1]?

I believe you have one or more elements (interes) and you wants to convert them into list of elements. You can use something like this.
import java.util.ArrayList;
import java.util.List;
public class DepositoBancario {
String banco;
List<String> interes;
public DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= v[0];
if(v[1] != null){
interes = new ArrayList<String>();
}
for(int i=1;i<n;i++)
interes.add(v[i]);
}
}
Note : Please consider the suggestion of markusw they are valuable.

First, You code won't compile unless You are using some custom implementation of List.
For what I can understand from You question it should be something like
import java.util.List;
import java.util.ArrayList;
public class DepositoBancario {
private String banco;
private List<String> interes;
DepositoBancario(String s) {
String[]v = s.split("[ :]"); // split input string by colon or space
if(v.length != 2) { // check if there are just two fields
throw new IllegalArgumentException("Invalid syntax, two fields expected: " + s);
}
banco = v[0];
interes = new ArrayList<String>();
interes.add(v[1]);
}
}

Related

Java 8 Stream | Add a value of the stream to another List/Collection without using foreach or any terminal Operation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So far i tried to add values from a stream to a list with peek() but later I found out that peek() is only used "to support debugging, where you want to see the elements as they flow past a certain point in a pipeline".
Now my question is whats the coding-convention here ?
Do I map it in a second stream or can I map it one String like my Code with Peek() ?
final int range = 9;
List <String> help = new ArrayList<String>();
//random numbers to fill help
for(int i = 5;i< range;i++)
{
help.add(String.valueOf(i+(i*2)+(i*(i+2))) );
}
List<Test> others = new LinkedList<>();
List<Test> tests = help.stream().map(s-> new Test(s,(int) Integer.valueOf("10")))
.peek(t->System.out.println(t.getText()))
.peek(t-> others.add(t)).collect(Collectors.toList());
The class Test looks like this:
public class Test
{
String text;
int id;
public Test(String text, int id) {
this.text = text;
this.id = id;
}
public String getText() {
return text;
}
public int getId() {
return id;
}
}
You could add that functionality to the lambda in the mapping part:
List<Test> tests = help.stream().map(
s-> {
Test t = new Test(s,(int) Integer.valueOf("10")));
System.out.println(t.getText());
others.add(t)
return t;
}
.collect(Collectors.toList());
That simply moves your extra steps into an existing step, avoiding any further loops etc

Using the Generic Type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My Instructor for my Data structures class has told me that there is a better way to implement using a Generic Data type in this method instead of casting everything to E. I am unable to figure out how this better way is implemented or exactly what she means. I know this method I wrote works but if there is a better way I would like to know.
public class GenericSortedArrayBag<E extends Comparable> implements Cloneable,Iterable<E> {
public int numPresents;
public int maxPresents;
private Object[] data;
public void delete(E k) {
boolean found = false;
for(int i=0; i <numPresents; i++) {
if(((E)data[i]).equals(k)) {
found = true;
}
if(found && i<numPresents - 1) {
data[i] = data[i+1];
}
else if(found) {
data[i] = null;
}
}
numPresents--;
}
Instead of
private Object[] data;
you can use
private E[] data;
That way you save the cast
if((data[i]).equals(k))

Access a linked list through a method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In this method I'm suppose to remove all zeroes from a linkedlist but I'm not sure how to access the linked list. I am not allowed to change the parameters of the method but I can change the return. How can I access the linkedlist to modify it?
public domino removeZero() {
// ****** student exercise
return this;
}
This is the line that calls the method:
train = train.removeZero();
The name of the class is domino.
Here is the complete program http://pastebin.com/EwNJj9mV
You can use some getter setter method
like store your linkedlist in one different class's static variable and than in your method get that static variable's value.
import java.util.LinkedList;
public class linkedListStorage {
private static LinkedList linkedList;
public static LinkedList getLinkedList() {
return linkedList;
}
public static void setLinkedList(LinkedList linkedList) {
linkedListStorage.linkedList = linkedList;
}
}
now when you get your linkedlist put it via setter method
import java.util.LinkedList;
class JunitTest {
public static void main(String[] args) {
// set linked list to storage class's variable
linkedListStorage.setLinkedList(your linked list variable);
}
}
now use your linked list in your method
public domino removeZero() {
// ****** student exercise
// get your linked list from storage class
LinkedList ll = linkedListStorage.getLinkedList();
return this;
}
I suspect you need to learn some basics about object oriented programming and then re-ask the question. The method you have included in your question (removeZero) is a member of a class (domino) that has fields you can access inside the method. In other words removeZero has access to the linked list because it's a method of the linked list object.
In this case the code would be something like:
public domino removeZero() {
domino first = null;
for (domino current = this; current.next != null; current = current.next) {
if (current.spot1 == 0 || current.spot2 == 0) {
if (current.back != null)
current.back.next = current.next;
if (current.next != null)
current.next.back= current.back;
} else if (first == null) {
first = current;
}
}
return first;
}
By the way, you should tell your teacher to use capital letters to start class names. It should be called Domino, not domino.

ArrayList strange behaviour [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can anybody tell me what's wrong with my code
latest_songs,top_songs and hit_songs are arraylist.song() is a static method in Parseurl where i fetch the json array.it working fine & return proper data.
latest_Songs = ParseUrl.song(url1);
Log.i("ring,latest=", latest_Songs.toString());
top_Songs = ParseUrl.song(url2);
Log.i("ring,top=", top_Songs.toString());
hit_Songs = ParseUrl.song(url3);
Log.i("ring,hits=", hit_Songs.toString());
it works fine when i run latest_songs and top_songs.problem is with hit_songs.as i write this in my project both arraylist(latest_songs and top_songs) data overrided with hits_songs.where i am doing wrong.
this is ParseUrl from where i retrieve data in each arraylist
public class ParseUrl {
static ArrayList<String> songs_List = new ArrayList<String>();
static ArrayList<String> songs_Names = new ArrayList<String>();
static ArrayList<String> songs_Urls = new ArrayList<String>();
static File tempFiles;
File ringtones;
public static ArrayList<String> song(String url) {
songs_Names.clear();
songs_Urls.clear();
JSONObject json = JsonParse.getSongfromUrl(url);
try {
JSONArray latestSongs = json.getJSONArray("ringtones");
for (int count = 0; count < latestSongs.length(); count++) {
JSONObject song = latestSongs.getJSONObject(count);
songs_List.add(song.toString());
JSONArray name = song.names();
songs_Names.add(name.toString());
String songUrl = name.toString();
String URL = songUrl.substring(2, songUrl.lastIndexOf("\""));
songs_Urls.add(song.getString(URL));
}
} catch (JSONException e) {
e.printStackTrace();
}
return songs_Names;
}
Your arraylist is a static variable inside your class.So there is only one arraylist in memory.Each time you call the song method , you are modifying the same list.That means your latest_songs,top_songs,hit_songs, all will be pointing to same list.That is the reason your list is getting over ridden.
Try creating a list inside your method and return it rather than going for static variables.
Are you changing the url value anywhere?
Because you are assigning ParseUrl.song(url) to all the three array lists. Unless url is changed somewhere, all three array lists will have the same value since ParseUrl.song(url) will give the same result.

How can I instantiate the class DefaultHashMap [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to access the DefaultHashMap class but getting error in the main method. Could anyone please tell me what is the problem?
import java.util.Random;
import java.util.*;
public class PythonToJava {
public static void main(String[] args) {
Random rm = new Random();
int i = rm.nextInt(1000);
HashMap<Integer,Integer> stats = new HashMap<Integer,Integer>();
DefaultHashMap<K,V> default = new DefaultHashMap<K,V>();
System.out.println("Random Number Generated is: " + i);
for (int j = 0; j<i; j++){
int value = rm.nextInt(500);
System.out.println("The value of VALUE is " + value);
}
}
}
class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
#Override
public V get(Object k) {
V v = super.get(k);
return ((v == null) && !this.containsKey(k)) ? this.defaultValue : v;
}
}
Please help me in rectifying the errors I'm encountering at the line with the code:
DefaultHashMap<K,V> default = new DefaultHashMap<K,V>();
The K and V are type parameters, and here, you need to use concrete types to substitute them, the same as when you are using HashMap.
K,V has to be objects
You cannot use variable default. Its a java reserve word.
You should read about java generics
http://docs.oracle.com/javase/tutorial/java/generics/why.html

Categories

Resources