Moving data to different methods - java

I am trying to figure out how to save a data in a submethod several times.
For example the code below is creating and array of strings then the array is moved to an arraylist five times. How to make the program save all strings 5 times. With other words, if I print out the array list newList .How to get the following output?
word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4, word0, word1, word2, word3, word4.
public static void main(String[] args) {
String[] list = new String[5];
for (int i = 0; i < list.length; i++) {
list[i] = "word" + i;
}
for (int i = 0; i < 5; i++) {
experiment(list);
}
}
public static void experiment(String[] list) {
ArrayList<String> arrList = new ArrayList<>();
for (int i = 0; i < list.length; i++) {
arrList.add(list[i]);
}
saveItAll(arrList);
}
public static ArrayList<String> saveItAll(ArrayList<String> counter) {
ArrayList<String> newList = new ArrayList<>();
newList = counter;
System.out.println(newList);
return newList;
}

You need to store it outside of the method and statically.
public class Test
{
static List<String> newList = new ArrayList<>();
public static void main(String[] args)
{
String[] list = new String[5];
for (int i = 0; i < list.length; i++) {
list[i] = "word" + i;
}
for (int i = 0; i < 5; i++) {
experiment(list);
}
System.out.println(newList);
}
public static void experiment(String[] list)
{
List<String> arrList = new ArrayList<>();
for (int i = 0; i < list.length; i++) {
arrList.add(list[i]);
}
saveItAll(arrList);
}
public static void saveItAll(List<String> counter)
{
newList.addAll(counter);
}
}
Another word here: You would not need the saveItAll method, since addAll is also doing the job here. Then you usually don't use Lists with there implementing type, you usually use the interface to define the type of it so the implementation would be switchable. That's what interfaces are for.

Related

Returning a substring from a method using java

Is there a way of returning substring from a string in java?
For example if I have a string:aadaa
It should return me: {a,a,d,a,a,aa,ad,aa,aad,ada,daa..}
This is my code:
String substring(String str1)
{
//String sbs="";
int len=str1.length();
for (int i=0;i<len;i++)
{
for (int j=i+1;j<=len;j++)
{
return(str1.substring(i, j));
}
}
I need the return statement to return a value from this method not to print it.
Please help.
To get all substrings of a given String using Java, you can use this GetSubtrings method:
public static ArrayList<String> GetSubstrings(String str) {
// set up any substring and add it to the ArrayList
ArrayList<String> subStrings = new ArrayList();
for (int i = 0; i < str.length(); ++i) {
for (int j = 1; j <= str.length() - i; ++j) {
subStrings.add(str.substring(i, i + j));
}
}
return subStrings;
}
An example on how to use it would be:
// stores all substrings
ArrayList<String> subStrings = new ArrayList();
// call method to get all substrings
subStrings = GetSubstrings("Test");
This will return an ArrayList which contains: { "T", "Te", "Tes", "Test", "e", "es", "est", "s", "st", "t" }
Whole example program:
package com.company;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// stores all substrings
ArrayList<String> subStrings = new ArrayList();
// call method to get all substrings
subStrings = GetSubstrings("Test");
}
public static ArrayList<String> GetSubstrings(String str) {
// set up any substring and add it to the ArrayList
ArrayList<String> subStrings = new ArrayList();
for (int i = 0; i < str.length(); ++i) {
for (int j = 1; j <= str.length() - i; ++j) {
subStrings.add(str.substring(i, i + j));
}
}
return subStrings;
}
}
As oRole's answer, if you don't want duplicate values, simply change List to HashSet. Since Java Set doesn't hold duplicate values.
public static HashSet<String> GetSubstrings(String str) {
// set up any substring and add it to the ArrayList
HashSet<String> subStrings = new HashSet();
for (int i = 0; i < str.length(); ++i) {
for (int j = 1; j <= str.length() - i; ++j) {
subStrings.add(str.substring(i, i + j));
}
}
return subStrings;
}

Java: First item of Array do not display correctly

I need to compare words to tweets and count how many times they appear on text.
I used two for cycle to compare ArrayList with words and ArrayList with tweets but the first word of ArrayList with words don't display correctly and don't want to count.
Output Image
It is supposed to champions word count twice
My code is:
Read txt with words and save on arraylist
public ArrayList <String> fread(String dir) throws FileNotFoundException, IOException {
Scanner s = new Scanner(new File(dir));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next().toLowerCase());
}
s.close();
return list;
}
Get Tweets and save them on arraylist
public ArrayList<String> showTimeLine() throws TwitterException {
List<Status> statuses = twitter.getHomeTimeline(new Paging (1,200));
ArrayList<String> allTweets=new ArrayList<String>();
for (Status status : statuses) {
allTweets.add(status.getText().replaceAll("https[^\\s]+","").toLowerCase());
}
return allTweets;
}
Compare two arrays:
public ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
for (int i = 0; i <palavras.size() ; i++) {
int count = 0;
for (int j = 0; j <tweets.size() ; j++) {
if (tweets.get(j).contains(palavras.get(i))){
count++;
}
}
numero.add(count);
result.add(palavras.get(i));
}
return result;
}
And print
for (int i = 0; i <result.size() ; i++) {
System.out.printf("%40s",result.get(i)+" "+numero.get(i)+"\n");
}
Static ArrayList:
static ArrayList<Integer> numero = new ArrayList<Integer>();
static ArrayList<String> result = new ArrayList<String>();
Thanks ! :)
In the method
public ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
for (int i = 0; i <palavras.size() ; i++) {
int count = 0;
for (int j = 0; j <tweets.size() ; j++) {
if (tweets.get(j).contains(palavras.get(i))){
count++;
}
}
numero.add(count);
result.add(palavras.get(i));
}
return result;
}
Your if-statement finds a single result and then ends. You can fix this like so
public static ArrayList<String> result(ArrayList<String>tweets, ArrayList<String> palavras){
for (int i = 0; i <palavras.size() ; i++) {
int count = 0;
for (int j = 0; j <tweets.size() ; j++) {
boolean isDone = false; //NEW
int tweetCharIter = 1; //NEW
while (!isDone){ //NEW
if (tweets.get(j).substring(tweetCharIter).contains(palavras.get(i))){ //ALTERED
tweetCharIter += tweets.get(j).substring(tweetCharIter).indexOf(palavras.get(i)) +1; //ALTERED
count++;
} else { //NEW
isDone = true; //NEW
}
}
}
numero.add(count);
result.add(palavras.get(i));
}
return result;
}

Printing empty brackets?

I have a simple program that should take two arrays, convert them into lists, and take out the values that are the same. For some reason though I am getting a value of:
[]
[]
[]
[]
Although the result should be "eggs", "lasers", "hats", "pie" - "lasers", "hats" which should get me a result of "eggs" "pie".
Here is my code:
public class Arraystring {
public static void main(String[] args) {
String[] things = { "eggs", "lasers", "hats", "pie" };
List<String> list1 = new ArrayList<String>();
for (String x : things) {
list1.add(x);
}
String[] thingstwo = { "lasers", "hats" };
List<String> list2 = new ArrayList<String>();
for (int i = 0; i < list2.size(); i++) {
list2.add(thingstwo[i]);
}
editlist(list1, list2);
}
public static void editlist(Collection<String> l1, Collection<String> l2) {
Iterator<String> it = l1.iterator();
while (it.hasNext()) {
if (l2.contains(it.next())) {
System.out.println("hui");
it.remove();
}
System.out.println(l2);
}
}
}
First your line in Arraystring {..}
for (int i = 0; i < list2.size(); i++) {
should be
for (int i = 0; i < thingstwo.length; i++) {
And then you are printing the wrong list in editlist(..):
System.out.println(l2);
should be
System.out.println(l1);

Java array I need your thought

Given an array of strings, return another array containing all of its longest strings.
For (String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};)
output will be
{"serm", "sazi" , "kart"}.
The following code is wrong, What can I do to fix it.
public class Tester {
public static void main(String[] args) {
Tester all = new Tester();
String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};
String [] y = all.allLongestStrings(x);
System.out.println(y);
}
String[] allLongestStrings(String[] input) {
ArrayList<String> answer = new ArrayList<String>(
Arrays.asList(input[0]));
for (int i = 1; i < input.length; i++) {
if (input[i].length() == answer.get(0).length()) {
answer.add(input[i]);
}
if (input[i].length() > answer.get(0).length()) {
answer.add(input[i]);
}
}
return answer.toArray(new String[0]);
}
}
I will give you solution, but as it homework, it will be only sudo code
problem with your solution is, you are not finging longest strings, but strings same size or bigger than size of first element
let helper = []
let maxLength = 0;
for each string in array
if (len(string) >maxLength){
maxLength = len(string);
clear(helper)
}
if (len(string) == maxLength)
helper.add(string)
}
return helper;
You can try below code
private static String[] solution(String[] inputArray) {
int longestStrSize = 0;
List<String> longestStringList = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != null) {
if (longestStrSize <= inputArray[i].length()) {
longestStrSize = inputArray[i].length();
longestStringList.add(inputArray[i]);
}
}
}
final int i = longestStrSize;
return longestStringList.stream().filter(x -> x.length() >= i).collect(Collectors.toList()).stream()
.toArray(String[]::new);
}

return multiple values java for removing last part of a word

In my code, fromright method checks the length of last[] and returns only one string. I want to return all matched values. What's the solution?
public static String last[]={"es","e","s"};
public static void main(String[] args) {
text tx=new text();
String checkString = "lives";
String fin=tx.fromright(checkString);
System.out.println("remaining: "+fin);
}
public String fromright(String wrd) {
String tmp="";
for (int i = 0; i < last.length; i++) {
tmp=wrd.substring(0, wrd.length()-last.length);
}
return tmp;
}
You are overriding your tmp variable in your for loop every time. So you can only get one result.
Use this instead or smth. similiar which can hold multiple values.
public List<String> fromright(String wrd) {
List<String> tmp= new ArrayList<String>();
for (int i = 0; i < last.length; i++) {
tmp.add(wrd.substring(0, wrd.length()-last.length));
}
return tmp;
EDIT:
This does not work anymore.
String fin=tx.fromright(checkString);
^
Replace it with
List<String> fin= new ArrayList<String>(tx.fromright(checkString));
And print out all values with this
for(String s : fin) System.out.println(s);
public List<String> fromright(String wrd) {
List<String> result = new ArrayList<>();
for (int i = 0; i < last.length; i++) {
if(wrd.endsWith(last[i]))
result.add(last[i]);
}
return result;

Categories