How to convert an int array to String with toString method in Java
What you want is the Arrays.toString(int[])
method:
import java.util.Arrays;
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
..
System.out.println(Arrays.toString(array));
There is a static Arrays.toString
helper method for every different primitive java type; the one for int[]
says this:
public static String toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (
"[]"
). Adjacent elements are separated by the characters", "
(a comma followed by a space). Elements are converted to strings as byString.valueOf(int)
. Returns"null"
ifa
is null.
Converting String Array to an Integer Array
You could read the entire input line from scanner, then split the line by ,
then you have a String[]
, parse each number into int[]
with index one to one matching...(assuming valid input and no NumberFormatExceptions
) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[]
will be represented by a 0
, these need to be removed in order to differentiate between a valid input value of 0
.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
Convert String to int array in Java the fast way
Using String.split()
is by far the most efficient when you want to split by a single character (a space, in your case).
If you are aiming for maximal efficiency when splitting by spaces, then this would be a good solution:
List<Integer> res = new ArrayList<>();
Arrays.asList(kraft.split(" ")).forEach(s->res.add(Integer.parseInt(s)));
Integer[] result = res.toArray(new Integer[0]);
And this works for any number of numbers.
What's the simplest way to convert a String Array to an int Array using Java 8?
For example:
static int[] parseIntArray(String[] arr) {
return Stream.of(arr).mapToInt(Integer::parseInt).toArray();
}
So take a Stream
of the String[]
. Use mapToInt
to call Integer.parseInt
for each element and convert to an int
. Then simply call toArray
on the resultant IntStream
to return the array.
Convert String to Integer(Object) Array Java
Rather than IntStream
, you still want the Stream
type (Stream<Integer>
specifically), so instead of mapToInt
, you should call map
. Then to convert the resulting Stream<Integer>
to an array, call toArray(Integer[]::new)
:
Arrays.stream(string.split(" "))
.map(Integer::parseInt)
.toArray(Integer[]::new);
Convert String array to an Int array and total it
Your input consists of alternating numeric and non-numeric data. And after splitting the line on white spaces with split("\\s+")
you are trying all the strings into int
. That will inevitably lead to NumberFormatException
at runtime.
To avoid that you need to add a filter()
to the stream to ensure that only strings that are comprised of digits will be parsed.
And since you are using int[] results
only as a source of the second stream that calculates the sum
then you should get rid of redundancy. There's no need to create a second stream and allocate in memory unused array.
Another mistake is that the scope of the variable sum
is limited to the while
loop. And according to your example of the input, a line will contain only at most only one digit. That doesn't make much sense and I think that wasn't your intention.
Here is one of the ways how to resolve these issues:
int sum = 0;
try(Stream<String> lines = Files.lines(inputFile.toPath())) {
sum = getSum(lines);
} catch (IOException e) {
e.printStackTrace();
}
Note that try-with-resources is a preferred way to deal with resources that implement AutoCloseable
. When execution of the try
block finishes (normally or abruptly) all resources will be closed.
Logic for calculating the sum:
public static int getSum(Stream<String> lines) {
return lines.flatMap(line -> Stream.of(line.split("\\s+")))
.filter(str -> str.matches("\\d+"))
.mapToInt(Integer::parseInt)
.sum();
}
That basically the answer to the question:
Convert String array to an Int array and total it
To fix other parts of your code you have to have a clear understanding of what you are trying to achieve. There is a lot of actions packed together in this code, you need to split it into separate methods each with its own responsibility.
The code for writing to the outputFile
seems to be unrelated to the process of calculating the sum. Basically, you are creating a copy of the inputFile
with only one additional line: "Number of months of the loan: " + String.valueOf(loanMonths)
.
If you insist these actions must be done at the same time, for instance, the inputFile
could be large, then it might be done like this:
try(BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
if (!line.isBlank()) {
sum += Integer.parseInt(line.split("\\s+")[1]);
}
}
writer.write("Number of months of the loan: " + String.valueOf(loanMonths));
} catch (IOException e) {
e.printStackTrace();
}
Note that in this case, Java 8 streams are not needed because a line can contain only a single value and there's nothing to process with a stream.
Related Topics
How to Match "Any Character" in Regular Expression
How to Deserialize Js Date Using Jackson
Random "Element Is No Longer Attached to the Dom" Staleelementreferenceexception
What Is the Purpose of the Java Constant Pool
Do I Need to Store the Salt with Bcrypt
Convert Arraylist into 2D Array Containing Varying Lengths of Arrays
What Are the Main Uses of Yield(), and How Does It Differ from Join() and Interrupt()
What Does the Colon (:) Operator Do
Is It Safe to Get Values from a Java.Util.Hashmap from Multiple Threads (No Modification)
Java Read Large Text File with 70Million Line of Text
Cast Object to Generic Type for Returning
Sorting an Array of Int Using Bubblesort
Annotation @Transactional. How to Rollback
Meaning of Delta or Epsilon Argument of Assertequals for Double Values
Jvm Option -Xss - What Does It Do Exactly
Best Way to Create Enum of Strings
Default Fetch Type for One-To-One, Many-To-One and One-To-Many in Hibernate