Reputation: 10385
Java. So I want to input an array of integers and then print out the max value using StringTokenizer. I know how to do this using integers, but when I try to do it with an array the String to int command (Integer.parseInt) fails me - cannot convert from int to int[].
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String strTmp;
StringTokenizer strTok;
while ((strTmp = in.readLine()) != null && strTmp.length() != 0) {
strTok = new StringTokenizer(strTmp);
int[] c;
c = Integer.parseInt(strTok.nextToken());
int max = 0;
for (int i = 0; i < c.length; i++) {
if (c[i] > max) {
max = c[i];
}
}
System.out.println(max);
}
}
}
How do I go about solving this or are there other commands I should be using?
Upvotes: 0
Views: 3131
Reputation: 12890
Integer.parseInt(String)
returns an integer, not an Integer array
. You have to store the return value Integer in an int variable like
int i = Integer.parseInt(String);
You have to iterate the integer array and set it's index value to the returned integer value
for (int i = 0; i < c.length; i++) {
c[i] = Integer.parseInt(strTok.nextToken());
if (c[i] > max) {
max = c[i];
}
}
Hope this helps!
Upvotes: 0
Reputation: 1502656
You seem to be confused about whether you actually want an array or not. You're parsing a single value, but trying to assign that int
to c
which is an array variable. You don't really need one, as you only need to remember the current maximum, and the value you've just parsed:
int max = Integer.MIN_VALUE;
while (strTok.hasMoreTokens()) {
int value = Integer.parseInt(strTok.nextToken());
if (value > max) {
max = value;
}
}
If you really want an array, then you'll need to know how many tokens there are before you parse them, which is tricky.
Another alternative would be to create a List<Integer>
:
// First parse everything...
List<Integer> values = new ArrayList<>();
while (strTok.hasMoreTokens()) {
values.add(Integer.parse(strTok.nextToken());
}
// Then you can find the maximum value in the list
Personally I prefer the first approach, if you only need to find the maximum value.
Upvotes: 2
Reputation: 6462
int[] c;
c = Integer.parseInt(strTok.nextToken());
You are trying to assign a single Integer object to an array of int
.
Rather, use int[index] = Integer.parseInt(strTok.nextToken());
Upvotes: 0