Formatting ArrayList of Integers - java

I currently have this code, but when it's printed, it prints the integers on different lines one right after another. How can I format this, so that it prints like this: [1, 2, 4, 5, 6]
I've tried converting the ArrayList to an array, but I must not being doing it correctly because it doesn't seem to be working.
import java.util.*;
public class PartBMod {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your array of integers (using commas to separate them, no spaces): ");
ArrayList<Integer> arrayList = new ArrayList<Integer>();
String str = new String(input.nextLine());
String[] array = str.split(",");
for (String i : array) {
arrayList.add(Integer.parseInt(i));
}
Collections.sort(arrayList);
for (Integer i : arrayList) {
System.out.println(i);
}
}

Your desired format is the default for ArrayList. You could use
System.out.println(arrayList);

Elliot's answer notwithstanding, if toString() didn't happen to be what you wanted, you could roll your own in just one statement:
System.out.println(
Arrays.stream(input.nextLine().split(","))
.mapToInt(Integer::parseInt)
.sort()
.mapToObj(String::valueOf)
.collect(Collectors.join(",", "[", "]")));

Do this simple way:
System.out.print("[");
for (int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i));
if(i != arrayList.size()-1)
System.out.print(", ");
}
System.out.println("]");

The reason your code isn't working the way you want it to is because you are using println. It will add a new line after printing each item. What I would do is something like this
String textToPrint = "[ ";
for (int i =0; i < arrayList.size(); i++) {
textToPrint += String.valueOf(i) + ", ";
}
textToPrint = textToPrint.substring(0, textToPrint.length() -2);
textToPrint += "]";
System.out.println(textToPrint);
This way you are adding each integer into a string to print.
Elliots' answer is cleaner and more efficient in this case, but this loop may be needed in other cases.
The substring line removes a trailing comma and space. IMO it's cleaner than adding an if statement into the for loop.

Related

Is there an easy way to eliminate the final comma in my output? Number Seperator

For another assignment i needed to program a "number seperator", that splits any given int value into all of its digits and returns it to the main class as a String.
I have the program up and running but there's a small problem with my output.
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
System.out.println("Input a Number: ");
int zahl = readInt();
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
System.out.print(ziffern.charAt(i) + ",");
}
}
}
The output of 1234 should be: 1,2,3,4
and the actual output is: 1,2,3,4,
At the risk of sounding extremely stupid, is there an easy fix to this?
How about printing first element without comma and rest in form ,nextElement like
one, two, three
^^^---------------- - before loop
^^^^^----------- - loop iteration
^^^^^^^---- - loop iteration
It can be achieved like:
if(ziffern.length()>0){
System.out.print(ziffern.charAt(0));
}
for(int i=1; i<ziffern.length(); i++){
System.out.print(", "+ziffern.charAt(i));
}
OR you can convert ziffern to String[] array first and use built-in solution which is: String.join(delimiter, data)
System.our.print(String.join(",", ziffern.split("")));
When it's the last iteration, just don't add it.
In the last iteration, it will make the comma empty so that you won't see it after the last value.
String comma=",";
for (int i = 0; i < ziffern.length(); i++) {
if (i == ziffern.length()-1) {
comma="";
}
System.out.print(ziffern.charAt(i) + comma);
}
with Java 8 and streams you can do it in a single command:
String join = Arrays.asList(ziffern.split(""))
.stream()
.collect(Collectors.joining(","));
System.out.println(join);
or with just plain java 8:
String join = String.join(",", ziffern.split(""));
System.out.println(join);
A simple one liner will do your job:
static String splitNumber(int zahl) {
return String.join(",", String.valueOf(zahl).split(""));
}
Quite often this occurs when you know you have at least two items to print. So here is how you could do it then.
String ziffern = splitNumber(zahl);
String output = ziffern[0];
for (int i = 1; i < ziffern.length(); i++) {
output = "," + ziffern[i];
}
System.out.println(output);
You can just output the string without the last character.
Your modified code should be:
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
int zahl = 1234;
String s="";
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
s+=ziffern.charAt(i) + ",";
}
System.out.println(s.substring(0,s.length()-1));
}

Accessing index values before and after symbol from input

I am trying to take the input and if there is an # symbol in the input then it finds the maximum of the integers before and after the # symbol. The maximum part I have no problem with but I do not know how to access and find the values before and after the # symbol.
import java.util.Scanner;
public class Max_Min {
public static void main(String[] args) {
//gets keyboard
Scanner keyboard = new Scanner(System.in);
//puts input into string
String inputString = keyboard.nextLine();
//splits string between characters
String[] splitInput = inputString.split("");
for (String s : splitInput) {
if(s.equals("#")){
//computes the maximum of the two integers before and after the #
}
}
//close keyboard
keyboard.close();
I did do a search to find something simliar (and im sure there is something) but could not find anything. If someone could help that would be great!
Try with this:
for (int i = 0; i < splitInput.length; i++){
if (splitInput[i].equals("#") && i != 0 && i != splitInput.length -1){
int max = Math.max(Integer.parseInt(splitInput[i - 1]), Integer.parseInt(splitInput[i + 1]));
}
//...
}
You could try:
String[] splitInput = inputString.split("#");
which would split your string at the #s.
Then you can do a iteration over your splitInput array and do a .length on each index.
You have written the simple for loop, with which you can only access the string, but not its index in the array. If you had the index, you could write:
int possibleMax = Integer.parseInt(splitInput[i - 1]) + Integer.parseInt(splitInput[i + 1]);
To get the index, there are two ways:
for (int i = 0; i < splitInput.length; i++) {
String s = splitInput[i];
...
}
Or:
int i = 0;
for (String s : splitInput) {
…
i++;
}
I don't like either version because both are more complicated than absolutely necessary, in terms of written code. If you would use Kotlin instead of Java, it would be:
splitInput.forEachIndexed { i, s ->
…
}
In Java this could be written:
forEachIndexed(
splitInput,
(i, s) -> …
);
The problem in Java is that the code inside the … cannot update the variables of the enclosing method. I'm not sure whether this will ever change. It would be possible but needs a lot of work by the language committee.
A simple way to do this would be
String input = "12#23";
String [] arr = input.split("#");
if (arr.length == 2) {
System.out.println("Max is "+Math.max(Integer.valueOf(arr[0]),Integer.valueOf(arr[1])));
}

How to iterate through an arraylist of an arraylist of strings?

I'm creating a program that allows users to interact with a file thats input. One of the options is to display the file. Below, I store the file into an arraylist first by creating arraylists consisting of lines, and then an inner arraylist separated of strings, separated by spaces.
Scanner sc = new Scanner(fileName);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] words = {};
words = line.split(" ");
ArrayList<String> lineArray = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
lineArray.add(words[i]);
}
fileByLine.add(lineArray);
}
sc.close();
I'm trying to print the contents of the arraylist, called fileByLine, as they appear in the file, but I'm not sure how to. Any suggestion?
case '1':
for(int i = 0; i < fileByLine.size(); i++){
for(int j = 0; j < fileByLine.[i].size(); j++){
System.out.print(fileByLine[i][j]);
} System.out.println("");
} break;
You are using bracket notation which is for arrays, you need to use get() for arraylists
for(int i = 0; i < fileByLine.size(); i++){
for(int j = 0; j < fileByLine.get(i).size(); j++){
System.out.print(fileByLine.get(i).get(j));
}
System.out.println("");
}
Since your container consist of String type you can just print it as follow:
System.out.println(fileByLine);
No need to loop through your collection. For example, let's say you have following list:
List<String> oneList = new ArrayList<>(Arrays.asList("1 2 3 4 5 6 7".split(" ")));
and you want to add it into another list:
List<List<String>> anotherList = new ArrayList<>();
anotherList.add(oneList);
After adding you would like to print it and here is how it looks:
System.out.println(anotherList);
Output: [[1, 2, 3, 4, 5, 6, 7]]
It prints because of String type if you keep any other custom type in your container and try to print it that will not work until you override toString() method.
If you need to iterate over two nested lists you can use this approach too:
Iterator<List<String>> outerIterator = anotherList.listIterator();
while (outerIterator.hasNext()) {
Iterator<String> innerIterator = outerIterator.next().listIterator();
while (innerIterator.hasNext()) {
String item = innerIterator.next();
System.out.print(item + " ");
}
System.out.println();
}
Or something like this as well...
for (List list : fileByLine) {
for (Object line : list) {
System.out.print(line);
}
System.out.println("");
}

Reducing For loops - Code Optimization

I am new to Java and looking for code optimization techniques. This code is giving the expected output using two for loops and I want to reduce/eliminate the loops (if possible).
public static void main(String[] args) {
String dummy = "Hello how are you";
String[] strArr = dummy.split(" ");
for(int i=0; i < strArr.length;i++){
String word = strArr[i];
for(int j=word.length(); j > 0; j--){
System.out.print(word.charAt(j - 1));
}
System.out.print(" ");
}
}
Output: olleH woh era uoy
Please advice.
Since the complexity of printing the output would remain the same, all you can do is to "hide" the loops into existing methods that do what you want, not eliminate them, because the amount of work the system needs to perform remains the same in terms of the number of characters that need to be processed.
You can hide the nested loop by using string reversal technique described in this Q&A. The outer loop can be pushed into String.join:
String[] data = {"quick", "brown", "fox"};
System.out.println(
String.join(
" "
, Arrays.stream(data)
.map(s -> new StringBuilder(s).reverse().toString())
.toArray(String[]::new)
)
);
Demo.
As I stated in my comment the complexity is already O(n) and you cannot get better because you need to read the input string. Anyway, there is a way to "unnest" the two for loops: reverse the whole string, split on spaces, and reverse the resulting array.
Example:
"Hello how are you"
"uoy era woh olleH"
"uoy" "era" "woh" "olleH"
"olleH" "woh" "era" "uoy"
Code:
public static void main(String[] args) {
String dummy = "Hello how are you";
int n = dummy.length();
StringBuilder sb = new StringBuilder(n);
while (--n >= 0) sb.append(dummy.charAt(n));
String[] tokens = sb.toString().split(" ");
n = tokens.length;
while (--n >= 0) System.out.print(tokens[n] + " ");
}
Instead, if you are after cools java 8 Stream tricks, read dasblinkenlight's answer.
This is another simple solution using StringTokenizer.
It takes only O(n).
public static void main(String[] args) {
System.out.println(reverseStringWordByWord("Hello How are you"));
}
public static String reverseStringWordByWord(String input) {
StringBuilder result = new StringBuilder();
StringTokenizer sToken = new StringTokenizer(input, " ");
while (sToken.hasMoreTokens()) {
StringBuilder thisToken = new StringBuilder(sToken.nextToken());
result.append(thisToken.reverse() + " ");
}
return result.toString();
}

Formatting a string array in java

I have a string array which has k elements. I want to print them out using System.out.format, but the issue is that I do not know k. So essentially, I want to use something like:
System.out.format("%s %s ... k times", str1, str2, ... strk);
(where k is a variable)
I was looking through the java documentation, but could not find a way to do this. Is there a simple way out?
Thanks!
you can use
System.out.format("%s". Arrays.toString(your_array));
Java 8:
String formatted = Stream.of(arrayOfStrings)
.collect(Collectors.joining(",","[","]"));
String formatted = Stream.of(arrayOfSomethingElse)
.map(Object::toString)
.collect(Collectors.joining(",","[","]"));
Use a loop:
for (String s : array) {
System.out.print(String.format("%s ", s));
}
System.out.println();
for(int i = 0; i < array.length; i++) {
System.out.print("%s ", array[i]);
}
Try:
StringBuilder sb = new StringBuilder();
for(String s : myArray){
sb.append(s).append(" ");
}
sb.append(myArray.length).append(" times");
System.out.println(sb.toString()); // print the string
Do you simply want to concatenate k strings with a space between each of the strings? You don't need System.out.format for that. You could simply create a loop to concatenate them together with a StringBuilder:
public String concatStrings(String... s) {
StringBuilder sb = new StringBuilder();
if (s.length > 0) {
sb.append(s[0]);
for (int i = 1; i < s.length; i++) {
sb.append(' ').append(s[i]);
}
}
return sb.toString();
}
I want to specify the number of characters that I want for each string. Something like %15s
That will only specify the padding for each String. If the String length is less than the value specified in the format specifier, then the full String is used. You could use substring
void displayArray(String[] str, int characters) {
for (String s: str) {
System.out.print(s.substring(0, Math.min(s.length(), characters)) + " ");
}
System.out.println();
}
That's typical toolbox code - code you often use and reuse, and best keep in a static-access utility class (such as StringUtil). Here's a generic function that works on all kinds of non-primitive arrays, and lets you specify the separator (space, comma, slash, whatever):
public static <T> void print (PrintStream out, String separator, T... elements) {
for (int i = 0; i < elements.length; i++) {
if (i > 0) {
out.print(separator);
}
out.print(elements[i]);
}
}
Example Usage:
String[] s = {"A", "B", "C", "D", "E"};
Integer[] n = {1, 2, 3, 4, 5}; //non-primitive
print(System.out, " ", s);
print(System.out, ", ", n);
You can use String.join() to format your array to your desired result.
System.out.println(String.join(" ", array));

Categories