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());
}
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.]
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.
Hi I want to put my prints in a for-loop. how to do it? So something like
if index = 0,1,2 print.
if index = 2,3,4 print.
if index = 4,5,6 print.
Code:
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.println("\n\nThis starts to look like calculations:");
System.out.print("\n" + objectList.get(0));
System.out.print(" "+ objectList.get(1));
System.out.print(" " + objectList.get(2) + " =");
System.out.print("\n\n" + objectList.get(2));
System.out.print(" " + objectList.get(3));
System.out.print(" " + objectList.get(4)+ " =");
System.out.print("\n\n" + objectList.get(4));
System.out.print(" " + objectList.get(5));
System.out.print(" " + objectList.get(6) + " =");
output:
This starts to look like calculations:
1 + 3432.123 =
3432.123 * 4535 =
4535 - 24.4 =
private String buildOperation(int pos){
String output;
if(pos == 0) {
output = "+";
}else if(pos == 1){
output = "*";
}else {
output = "-";
}
return output;
}
List<Object> objectList = new ArrayList(res);
for(int i = 0; i < objectList.size()-1; i++){
System.out.println(objectList.get(i) + buildOperation(i) + objectList.get(i+1) + "=");
}
Additionaly I'll use a HashMap with the operations to avoid all if/else conditions
Map<Integer,String> operations = new HashMap{}
operations.put(0,"+");
operations.put(1,"*");
operations.put(2,"-");
System.out.println(objectList.get(i) + operations.get(i) + objectList.get(i+1) + "=");
}
Final solution now the String size does not matter anymore.
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\n\nThis starts to look like calculations:");
int maxi= objectList.size();
maxi = maxi -2;
System.out.println("\n\nmaxi = " + maxi);
for (int i = 0; i < maxi; i+=2) {
System.out.println("");
System.out.println(i);
System.out.print("\n\n" + objectList.get(i));
System.out.print(" " + objectList.get(i + 1));
System.out.print(" " + objectList.get(i + 2)+ " =");
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.
I am having trouble with the logic I think. My results are not adding up correctly. Can someone please help? The problem is in the arrayList.size, nums.length or something. I entered 50 40 60 as my integers.
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + list.get(arraySize)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}
}
You are sorting list so it will return last value from sorted list. Collections.sort(list) is sorting asc so you get max number from the list. First approach,
1) Either you have to manage origanal list before sorting like
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
And get the value from ori.
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
2) Second approach, Create variable which will store temp last entered value. you can use it.
Might it helps!!
So your example like:
public static void main(final String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}