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?
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.
See more on this question at Stackoverflow