Try:
import java.util.Scanner;
public class NumAverage {
public static void main (String [] args)
{
//int a,b;
int[] numbers = new int [10];
Scanner numreader = new Scanner(System.in);
System.out.println("Enter 10 num");
for (int i = 0; i < numbers.length; i++) {
// Without the try and catch you get the appropriate exception,
// NumberFormatException in this case
String str = numreader.next();
numbers[i] = Integer.parseInt(str);
//try {
// numbers[i] = Integer.parseInt(numreader.next());
//} catch(NumberFormatException e) {
// number[i] = 0; // or whatever you want
//}
}
}
}
Answer from rendon on Stack OverflowTry:
import java.util.Scanner;
public class NumAverage {
public static void main (String [] args)
{
//int a,b;
int[] numbers = new int [10];
Scanner numreader = new Scanner(System.in);
System.out.println("Enter 10 num");
for (int i = 0; i < numbers.length; i++) {
// Without the try and catch you get the appropriate exception,
// NumberFormatException in this case
String str = numreader.next();
numbers[i] = Integer.parseInt(str);
//try {
// numbers[i] = Integer.parseInt(numreader.next());
//} catch(NumberFormatException e) {
// number[i] = 0; // or whatever you want
//}
}
}
}
This is what I would do for your case.
int[] numbers = new int[10];
Scanner numreader = new Scanner(System.in);
System.out.println("Enter 10 numbers");
// Get User Input
for (int i = 0; i < numbers.length; i++) {
try {
numbers[i] = Integer.parseInt((String) numreader.nextLine());
} catch (NumberFormatException numFormatE) {
System.out.println(numFormatE.getMessage() + "cannot be converted to integer");
i = i - 1; // Restart current iteration.
}
}
numreader.close();
// Loop through the number to get sum of the number.
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
However, if you want to combine sum in the main loop, this should work as well:
int[] numbers = new int[10];
int sum = 0;
Scanner numreader = new Scanner(System.in);
System.out.println("Enter 10 numbers");
// Get User Input
for (int i = 0; i < numbers.length; i++) {
try {
numbers[i] = Integer.parseInt((String) numreader.nextLine());
} catch (NumberFormatException numFormatE) {
System.out.println(numFormatE.getMessage() + "cannot be converted to integer");
i = i - 1; // Restart current iteration.
}
sum += numbers[i]; // Add the number in loop
}
System.out.println(sum);
numreader.close();
UPDATE: FIXED CODE FORMATTING
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.
Line by line
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
With the Arrays.stream() alternative as
int [] v = Arrays.stream(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
However much better for parsing bigger chunks of text is
int [] v = Pattern.compile(",\\s+").splitAsStream(line)
.mapToInt(Integer::parseInt)
.toArray();
As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.
See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next โผ:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
โผ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
โโโโโโโโโ
Notes
โโ1. Lambda Expressions in The Java Tutorials.
โโ2. Java SE 8: Lambda Quick Start
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Using Java 8's stream library, we can make this a one-liner (albeit a long line):
String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).
You have used numbers instead of array, where numbers is a String. Also, I would suggest using a better name than array for naming an array
The question has mutated a bit, but here is a potential suggestion to resolve the invalid number format. Please note that file encoding may also play a role. It is also possible to strip other characters from the input via something like
String rawValue = alle_zahlen[i].replaceAll("[^-?\\d]+", "");
Also, good practice is to always use braces, so I've added them
for(i = 0; i < alle_zahlen.length; i++) {
String rawValue = alle_zahlen[i].trim();
try {
int value = Integer.parseInt(rawValue);
max = Math.max(max, value);
// NOTE: instead of Math.max, can also do (which is essentially what
// Math.max() does)
// max = max > value ? max : value;
} //try
catch (NumberFormatException e) {
e.printStackTrace();
}
} //for
System.out.println("Die groeste Zahl ist: " + max);
If you'd like to use Java 8 Streams, you could also do:
System.out.println("Die groeste Zahl ist: " +
Arrays.stream(alle_zahlen)
.mapToInt(s -> Integer.parseInt(s.replaceAll("[^-?\\d]+", "")))
.max()
.getAsInt());
Both approaches tested against a mock input of:
final String numbers = "33 \n123\n0\n55\n800\n-55\n-1\n777\n";
final String[] alle_zahlen = numbers.split("\\n");
I would suggest using a regular expression, capturing the elements you want using groups. The example below creates a list of Person objects instead of individual lists of Strings - encapsulating the data as other posters have suggested:
List<Person> people = new ArrayList<Person>();
String regexpStr = "(\\[([0-9]+),\\s*([0-9a-zA-Z]+),\\])";
String inputData = "[11, john,][23, Adam,][88, Angie,]";
Pattern regexp = Pattern.compile(regexpStr);
Matcher matcher = regexp.matcher(inputData);
while (matcher.find()) {
MatchResult result = matcher.toMatchResult();
String id = result.group(2);
String name = result.group(3);
Person person = new Person(Long.valueOf(id), name);
people.add(person);
}
And a simple class to encapsulate the data:
public class Person {
private Long id;
private String name;
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
// TODO equals, toString, hashcode...
}
Two ArrayLists? I think you need one List containing object type Item with id and name attributes.
If you parse id and name individually, without encapsulating them into an obvious object, you aren't thinking in terms of objects.
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"ifais null.
Very much agreed with @Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this
String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");
and now you have a String which can be parsed back to java.lang.Number, for example,
long veryLongNumber = Long.parseLong(intStr);
Or you can use the java 8 streams, if you hate regex,
String strOfInts = Arrays
.stream(intArray)
.mapToObj(String::valueOf)
.reduce((a, b) -> a.concat(",").concat(b))
.get();
The problem you have is that you create a new array in loop. You should take it out and initialized.
String[] num = sNums.split(" ");
double[] numbers = new double[num.length]; // The valid place for loop
for (int i = 0; i < num.length; ++i)
{
numbers[i] = Double.valueOf(num[i]);
}
for(double item: numbers) {
out.print(item + " ");
}
You're recreating the array each time in the for loop. Also you're using a for each at the second for and not using it, using i instead. That would not compile since i was never declared in that scope.. Anyway I suggest you forget about arrays in Java and use Lists, they're much more convenient.
sNums = scanString.nextLine();
final String[] num = sNums.split(" ");
final List<Double> numbers = new ArrayList<Double>();
for (final String cur: num) {
numbers.add(Double.valueOf(cur));
}
for(final Double item: numbers) {
out.print(item + " ");
}