How can i read 1,A,5,B with scanner and put it while reading in a string and an int vector in Java? [closed]

StackOverflow https://stackoverflow.com/questions/23681277

  •  23-07-2023
  •  | 
  •  

سؤال

So, i have this input at once: 1,A,5,B,10,A,8,A,17,B,17

I have these 2 lists:

String[] bidderName = new String[100];
int[] bidValue = new int[100];

I want, as i read this at once, to be able to store the numbers(1,5,10 etc.) in the bidValue list, and the names(A,B, etc.) in the biddername list.

How can i do this using java.util.Scanner, or anything else?

Than you in advance. Respects!

هل كانت مفيدة؟

المحلول

I assume that the letters are the bidder names,
and that your input starts with a bidder name.

public class Test055 {

    public static void main(String[] args) {
        String input = "A,5,B,10,A,8,A,17,B,17,B,1";
        String[] bidderName = new String[100];
        int[] bidValue = new int[100];

        String[] data = input.trim().split(",");
        int k = 0;
        for (int i = 0; i < data.length; i += 2) {
            bidderName[i/2] = data[i];
            bidValue[i/2] = Integer.parseInt(data[i + 1]);
            k++;
        }

        for (int i = 0; i < k; i++) {
            System.out.println(bidderName[i] + " // " + bidValue[i]);
        }
    }

}

نصائح أخرى

You could use a Scanner, but I wouldn't. The input is short enough (unless you have thousands of these) to read it in once and use Java regular expressions:

String s = "1,A,5,B,10,A,8,A,17,B,17";
String[] split = s.split(",");
for (String current : split) {
    if (current.matches("^\\d+$")) {
        System.out.println("handle number " + current);
    } else
        System.out.println("handle letter " + current);
}

Consider using an ArrayList rather than an array so you don't have to know the number of elements in each "array" up front.

First try to do it by yourself

Split the string using ',' use split(",") then you will get string array which contains both letters and numbers if you are sure that sequence follows same pattern add every odd index tokens to int array using Integer.parseInt() put even indexes directly to your array

You don't specify where the input is coming from, but for example, if it's coming from System.in, you could do something like this:

String[] bidderName = new String[100];
int[] bidValue = new int[100];
int bvIndex = 0;
int bnIndex = 0;    

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {
   if (scanner.hasNextInt()) {
       bidderValue[bvIndex++] = scanner.nextInt();
   else {
       bidderName[bnIndex++] = scanner.next();
   }
}

You would want some sort of terminal condition in addition to scanner.hasNext(), but that's up to you to determine.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top