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 2 years ago.
Improve this question
I'm coding a method that takes as input an array of integers and returns another array of strings, each of which denotes a non-empty prefix of the input array. For example, if the input
array is:
<3, 1, 4>
Then the output or returned array of string values should be:
<"[3]", "[3, 1]", "[3, 1, 4]">
There is an error in my code that I can't seem to find
public static String[] getAllPrefixes(int[] numbers) {
String[] result = null;
String[] arr = new String[numbers.length];
String seq = "" + numbers[0];
for (int i = 0; i < numbers.length; i++) {
arr [i] = "[" + seq + "]";
seq += ", " + numbers [i + 1];
}
result = arr;
return result;
}
Your code has some problems
In this line seq += ", " + numbers [i + 1]; when the loop is in the last item i+1 will be out of index
When you initialized seq you added the first item in the array so in your loop you should ignore this item and start from i = 1, you should also add this item in the arr array and in your loop you should update req first then add to arr so the final code will be like this
public static String[] getAllPrefixes(int[] numbers) {
String[] result = new String[numbers.length];
String seq = "" + numbers[0];
result[0] = "[" + seq + "]";
for (int i = 1; i < numbers.length; i++) {
seq += ", " + numbers[i];
result[i] = "[" + seq + "]";
}
return result;
}
you can also use StringBuilder instance of string for appending and the code will be like
public static String[] getAllPrefixes(int[] numbers) {
String[] result = new String[numbers.length];
StringBuilder seq = new StringBuilder("" + numbers[0]);
result[0] = "[" + seq + "]";
for (int i = 1; i < numbers.length; i++) {
seq.append(", ").append(numbers[i]);
result[i] = "[" + seq + "]";
}
return result;
}
Note: Search for String vs StringBuilder
You must be getting ArrayIndexOutOfBoundException, and this is because of seq += ", " + numbers[i + 1] line.
For example let's say length of the numbers array is 3, then your for loop will run till i=2 in that case your numbers[i+1] will be numbers[3] which doesn't exists and it will give an exception.
Related
so I'm having a small problem in java. I have something like
"Victor Fleming"
"Gone With"
"With The"
"The Wind."
So what the sentence should actually look like is
"Victor Fleming"
"Gone with the wind."
Therefore I'm looking to form a single sentence, by words that are adjacent and the same. If no adjacent same word is detected then the sentence will be separated as in "Victor Fleming" case where Fleming is not the same with Gone, so a new sentence is starting. What I've written so far:
List<String> separatedText = new ArrayList<>();
int i = 0;
while (i < mergedTextByHeightColor.size()) {
if ((i < (mergedTextByHeightColor.size() - 3)) && !(mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
separatedText.add(mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1));
i = i + 2;
}
String concatStr = "";
while ((i < (mergedTextByHeightColor.size() - 3)) && (mergedTextByHeightColor.get(i + 1).equals(mergedTextByHeightColor.get(i + 2)))) {
if (concatStr.contains(mergedTextByHeightColor.get(i))) {
concatStr = mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
} else {
concatStr = mergedTextByHeightColor.get(i) + " " + mergedTextByHeightColor.get(i + 1) + " " + mergedTextByHeightColor.get(i + 3);
}
i = i + 3;
}
separatedText.add(concatStr);
}
We can store the sentences in a String array, then loop through each one.
Inside the loop, we check whether the last word of the last item (by splitting it into an array with .split(" "), then getting the last element) is equal to the first word of the current item. If it is, we first remove the first word of the current item, then append it to a StringBuilder.
If it isn't, then we append the StringBuilder's value to the list, append the current element, and move on.
String[] sentences = {"Victor Fleming", "Gone With", "With The", "The Wind."};
List<String> newsentences = new ArrayList<>();
StringBuilder str = new StringBuilder();
for(int i = 0; i < sentences.length; i++) {
String cur = sentences[i];
if(i != 0) {
String[] a = sentences[i-1].split(" ");
String[] b = cur.split(" ");
String last = a[a.length-1];
String first = b[0];
if(last.equalsIgnoreCase(first)) {
str.append(cur.substring(first.length()));
}else {
newsentences.add(str.toString());
str = new StringBuilder();
str.append(cur);
}
}else {
str.append(cur);
}
}
newsentences.add(str.toString());
System.out.println(Arrays.toString(newsentences.toArray()));
Output:
[Victor Fleming, Gone With The Wind.]
public static void main(String[] args) {
String word;
String[] RobinWords = {"Hole In A Donut", "Bankruptcy", "Popcorn", "Ravioli", "Hijack", "Camouflage", "Key Hole", "New Year's Eve", "Trampoline", "Zorro", "Hallucination", "Alter Ego", "Backfire", "Batman"};
Random rand = new Random();
word = RobinWords [rand.nextInt(RobinWords.length)];
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
System.out.println("Holy " + word + ", Batman!");
}
It might seem a little silly but I couldn't figure out how to make the output to be different from one another.
What you likely meant to do
for (int i = 0 ; i < 5 ; i++)
{
word = RobinWords[rand.nextInt()];
System.out.println("Holy " + word + ", Batman");
}
This code will select a randomized index, send it to your array, store that Index's corresponding element in a String then print the string.
Put it in a loop, and get a new random word on each iteration.
String[] robinWords = { "Hole In A Donut", "Bankruptcy", "Popcorn", "Ravioli", //
"Hijack", "Camouflage", "Key Hole", "New Year's Eve", "Trampoline", //
"Zorro", "Hallucination", "Alter Ego", "Backfire", "Batman" };
Random rand = new Random();
for (int i = 0; i < 5; i++) {
int index = rand.nextInt(robinWords.length);
System.out.printf("Holy %s, Batman!%n", robinWords[index]);
}
Note that I have tried to improve the readability of your code by using a more standard name for robinWords and using printf instead of String concatenation. If you need five unique phrases, then you should probably prefer a Set; and assuming you're using Java 8+, you could do something like
Set<String> wordSet = new LinkedHashSet<>();
Random rand = new Random();
while (wordSet.size() < 5) {
int index = rand.nextInt(robinWords.length);
wordSet.add(robinWords[index]);
}
wordSet.stream().forEachOrdered(word ->
System.out.printf("Holy %s, Batman!%n", word));
Try this
System.out.println("Holy " + RobinWords [rand.nextInt(RobinWords.length)] + ", Batman!");
Because when rand.nextInt() execute it only generate random number once
I hava a code similar to the code below.
I want to print all iterations' output together, not separately.
Is there anybody here to help me with it?
HashMap<String, String> myHashMap = new HashMap <String, String>();
for (int j = 0; j < x.length(); j++)
int firstElement = 0;
int secondElement = 1;
if (myArray.length() > 0) {
String first = myArray.get(firstElement).toString();
String last = myArray.get(secondElement).toString();
//System.out.println(first + " --> " + last);
boolean a = Info.contains("xxx");
boolean b = Info.contains("yyy");
if( a || b ) {
//System.out.println(first + " --> " + last);
count++;
myHashMap.put(first, last);
System.out.println(count + "\t" + first);
total = total + " " + first;
}
}
}
Here I can print the output for each iteration.
But I need to print all together. Is there any way to save them into a HashMap and print them all together?
Assuming your code works correctly, this is one of the possible ways:
StringBuilder sb = new StringBuilder(); // Defined outside of the for loop
...
if( a || b ) {
//System.out.println(first + " --> " + last);
count++;
myHashMap.put(first, last);
System.out.println(count + "\t" + first);
total = total + " " + first;
sb.append(count).append("\t").append(first).append("\n");
}
...
System.out.println(sb.toString()); // Print out the output after the for loop.
public String foodstats (){
String foodstats = "";
for ( int i = 0; i < consumables.size(); i++){
foodstats = "Name: " + consumables.get(i).getName() + "\tNutrition: " + consumables.get(i).getNValue() + "\tStamina: " + consumables.get(i).getStamina() + "\n" ;
}
return foodstats;
}
So this returns: Name: Water Nutrition: 30 Stamina : 15
I realize why its doing this, the second time the for loop runs through it replaces the first item's stats and returns only the replaced stats.
Is there a way around this? I need to return all the item's stats based on the array list size.
I think what you are looking for is a StringBuilder, more efficient in that case than += concatenation :
public String foodstats (){
StringBuilder foodstats = new StringBuilder();
for ( int i = 0; i < consumables.size(); i++){
foodstats.append("Name: " + consumables.get(i).getName() + "\tNutrition: " + consumables.get(i).getNValue() + "\tStamina: " + consumables.get(i).getStamina() + "\n");
}
return foodstats.toString();
}
Make a StringBuilder and use append(...) in the loop. Once you are done, call toString() on the result, like this:
StringBuilder res = new StringBuilder();
for ( int i = 0; i < consumables.size(); i++){
res.append("Name: " + consumables.get(i).getName() + "\tNutrition: " + consumables.get(i).getNValue() + "\tStamina: " + consumables.get(i).getStamina() + "\n");
}
return res.toString();
Note: you could use foodstats += ... syntax, too, but that would be inferior, because each iteration of the loop would create a throw-away temporary object.
public String foodstats()
{
StringBuilder foodstats = new StringBuilder();
for (int i = 0; i < consumables.size(); i++)
{
foodstats.append("Name: ");
foodstats.append(consumables.get(i).getName());
foodstats.append("\tNutrition: ");
foodstats.append(consumables.get(i).getNValue());
foodstats.append("\tStamina: ");
foodstats.append(consumables.get(i).getStamina());
foodstats.append("\n");
}
return foodstats.toString();
}
I was hoping someone could help me out with a small problem I am having in java. I have a List and an ArrayList that I would like to output to a file with the first element of each, printed next to one another. Here is what I have so far:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for(String unique:uniqueList){
out.write(unique + "\r");
}
ArrayList<Integer>subtr=new ArrayList<Integer>();
out.write("The number: " + subtr + "\r");
This results in this output:
A
B
C
D
E
F
The number: [1, 2, 3, 4, 5, 6]
But I would rather it be like this:
A The number: 1
B The number: 2
...etc.
I am not really sure where to start on how to get the output format like that. I tried putting both sets of values into arrays but I just ended up confusing myself... Which is how I ended up here. Any help would be super appreciated.
Simply do this:
String br = System.getProperty("line.separator");
for (int i = 0, n = Math.min(uniqueList.size(), subtr.size()); i < n; i++)
out.write(uniqueList.get(i) + " The number: " + subtr.get(i) + br);
Something like this:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<Integer> subtr = new ArrayList<Integer>();
int length = Math.min(uniqueList.size(), substr.size());
for (int i = 0; i < length; i++) {
out.write(uniqueList.get(i) + " The number: " + substr.get(i) + "\r");
}
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<Integer>subtr=new ArrayList<Integer>();
for (int i = 0; i < uniqueList.size(); i++){
out.write(uniqueList.get(i) + "\r");
out.write("The number: " + subtr.get(i) + "\n");
}
NOTE: This assumes that both lists have the same number of elements. If they are not, you would iterate to Math.min(uniqueList.size(), subtr.size()).
This should do it:
int maxLength = Math.min(uniqueList.size(), subtr.size());
for(int i = 0; i < maxLength; i++)
{
out.print(uniqueList.get(i) + " The number: " + subtr.get(i) + "\r");
}
The efficient way is to maintain a HashMap with uniqueList as keys and subtr as values. Then iterate over a map.
Map<String,Integer> map = new HashMap<String,Integer>();
for (int i = 0; i < uniqueList.size(); i++){
map.put(key, subtr.get(i));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
out.println(entry.getKey() + " The Number : " + entry.getValue());
}