Блог пользователя bdub

Автор bdub, 13 лет назад, По-английски

==Java Noob

ok, I'm trying to learn Java but am having some early issues here — can someone please tell me why this code returns WA on problem 9 (lots of inputs) but works fine when I revert to the commented out code (with some mods of course) and use what I'm hearing is supposed to be a legacy and discouraged class — StringTokenizer ?

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer;

public class CROC2013Round2Div2A {

public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int n = Integer.parseInt(br.readLine());
    String[] arr = br.readLine().split(" ");

    //StringTokenizer str = new StringTokenizer(br.readLine());
    //int[] arr = new int[n];
    //for (int i = 0; i < n; i++) arr[i] = Integer.valueOf(str.nextToken());

    Arrays.sort(arr);

    for (int i = 1; i < arr.length; i++)
        if (Integer.valueOf(arr[i]) % Integer.valueOf(arr[0]) != 0) {
            System.out.println(-1);
            return;
        }
    System.out.println(arr[0]);
}

}

At first I had even skipped the BufferedReader for just a Scanner but was thinking maybe it was a size constraint... now I'm just all kinds of confused

  • Проголосовать: нравится
  • -18
  • Проголосовать: не нравится

»
13 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Ok, I figured it out. Array sort on strings returns non-numeric order based on length of the string rather than actual numerical value. So it wasn't a sizing issue at all.

This does, however, bring me to another question. Am I oversimplifying my code with something like this:

Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] sarr = sc.nextLine().split(" ");

it seems like most of what I am seeing posted is much more complicated than this... I feel like I must be overlooking something important ?