如何从Java中的一个输入提示将多个值转换为数组?

时间:2018-10-02 03:50:29

标签: java arrays

我在让程序一次接受信用卡号并将每个号码存储在数组中时遇到问题。每当我输入值时,我都会得到“ java.lang.NumberFormatException:对于输入字符串:“”,因为我是JAVA的新手,所以需要您的帮助。

import java.util.Scanner;
import javax.swing.*;
import java.util.ArrayList;
public class Credit_Card_eval

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


      int Sum=0;
      int Count=0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter your credit card number");
      String input = sc.nextLine();
      int[]CC =new int[15];
      String[] Creditstring = input.split("");

       for (int i=0;i<=15;i++){
           Count=Count++;
           CC[i]= Integer.parseInt(Creditstring[i]);
        }
        for (int i=0; i<15;i++){
            if(CC[0]==4)
            System.out.println("Your Card is a Visa Card");
            else if (CC[0]==5)
             System.out.println("Your Card is a Master Card");
            else if (CC[0]==3 && CC[1]==7)
             System.out.println("Your Card is American_Express");
            else if (CC[0]==6)
             System.out.println("Your Card is a Discover Card");
             else
             System.out.println("Your Card is unknown");
            }

      sc.close();


}
}

3 个答案:

答案 0 :(得分:0)

您根本不需要拆分。

  String input = sc.nextLine();
  int[] CC =new int[16];

   for (int i=0;i<=15;i++) {
       Count++;
       CC[i]= Character.getNumericValue(input.charAt(i));
    }

即使您可以完全避免使用Integer数组。代码将很简单:

  String input = sc.nextLine();

  for (int i=0; i<=15; i++) {            
    if(input.charAt(0) == '4')
        System.out.println("Your Card is a Visa Card");
    else if (input.charAt(0)=='5')
         System.out.println("Your Card is a Master Card");
    else if (input.charAt(0) =='3' && input.charAt(1)=='7')
         System.out.println("Your Card is American_Express");
    else if (input.charAt(0) =='6')
         System.out.println("Your Card is a Discover Card");
    else
         System.out.println("Your Card is unknown");
  } 

答案 1 :(得分:0)

(一般来说)您可能会遇到问题,因为信用卡号太大而无法容纳一个整数。

整数只有32位,因此它们最多只能达到〜2 ^ 31

而16位数字(大致)在2 ^ 50-2 ^ 52范围内

尝试使用长整数(64位)代替整数。

答案 2 :(得分:0)

您不需要第二个循环。因为它总是只检查0th和1st索引。就您而言,同一循环运行15次。

    int[] CC = new int[input.length()];      

    for (int i = 0; i < input.length(); i++) {
        Count++;
        CC[i]=Character.getNumericValue(input.charAt(i));
    }

    if (CC[0] == 4) {
        System.out.println("Your Card is a Visa Card");
    }else if (CC[0]== 5) {
        System.out.println("Your Card is a Master Card");
    } else if (CC[0] == 3 && CC[0] == 7) {
        System.out.println("Your Card is American_Express");
    } else if (CC[0] == 6) {
        System.out.println("Your Card is a Discover Card");
    } else {
        System.out.println("Your Card is unknown");
    }