简体   繁体   中英

How do I extract a single digit from a string of digits?

Example:

String number = "1234567890123456";

How do I store the second to last digit by itself in a int type variable?

Detailed:

for (int i = number.length()-2; i>-1; i-=2)
    int x = (Extract the  number) at i;

How do I do this?

Here's the code:

package creditcard;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class Card {

    //Declarations
    private String cardNumber;
    private boolean test = false;
    private String cardType = "Unknown";

    public Card(){
        cardNumber = "0";
    }//end Default Constructor

    public Card(String input){
        cardNumber = input;
    }//end Constructor

    //
    public void typeMatcher(){
        if (cardNumber.startsWith("37"))
            cardType = "American Express";
        if (cardNumber.startsWith("4"))
            cardType = "Visa";
        if (cardNumber.startsWith("5"))
            cardType = "Mastercard";
        if (cardNumber.startsWith("6"))
            cardType = "Discover";
    }//end typeMatcher

    // Returns true if card number is Valid.
    public boolean isValid(String cardNumber){
        if (cardNumber.length() > 12 && cardNumber.length() < 17)
            if((sumOfDoubleEvenPlace(cardNumber)+sumOfOddPlace(cardNumber))/10==0)
                test = true;
        return test;
    }//end isValid

    // Get result from Step 2.
    public int sumOfDoubleEvenPlace(String cardNumber){
        int sum = 0;
        int num = 0;
        for (int i = cardNumber.length()-2; i>-1; i-=2){
            num = Integer.parseInt(cardNumber.substring(i,i+1));
            if (num<10)
                sum+=(num*2);
            else
                sum+=getDigit(num);
        }//end for
        System.out.println(sum);
        return sum;
    }//end SumOfDoubleEvenPlace

    // Return this number if it is a single digit
    // Otherwise return the sum of the two digits.
    public int getDigit (int num){
        int no1 = num/10;
        int no2 = num%10;
        return no1+no2;
    }//end getDigit

    // Returns sum of odd place digits in number.
    public int sumOfOddPlace(String cardNumber){
        int sum = 0;
        for (int i = cardNumber.length()-1; i>-1; i-=2)
            sum += Integer.parseInt(cardNumber.substring(i,i));
        System.out.println(sum);
        return sum;
    }//end sumOfOddPlace

    public void writeToFile(){
        try{
            FileWriter fw = new FileWriter("G:\\Output.txt",true);
            BufferedWriter bw = new BufferedWriter(fw);
            if (isValid(cardNumber)){
                bw.write(cardNumber+" is a valid "+cardType+" card.");
                bw.newLine();
            }//end if
            else{
                bw.write(cardNumber+" is an invalid "+cardType+" card.");
                bw.newLine();
            }//end else
            bw.close();
            System.out.println("Success");
        }//end try

        catch(IOException ioe){
            ioe.printStackTrace();
        }//end catch

    }//end outputToFile

}//end Card

The goal is to check if a credit card number is valid (School project)

只需将子字符串 / 字符放在所需的数字上并对其进行解析...

int d = Integer.parseInt(number.substring(start, start+1))

Just do this:

int x = number.charAt(i) - '0'

Integer.parseInt is overkill here.

Your substring code in method sumOfOddPlace has a flaw:

  sum += Integer.parseInt(cardNumber.substring(i,i));

that should be

  sum += Integer.parseInt(cardNumber.substring(i,i+1));

This is probably the cause of your format exception.

There's a little method called "charAt()" that'll do what you want.

 char c = someString.charAt(someString.length - 2);

Then you need to convert the character to an integer.

Pick @Andrew White's answer because that makes the integer conversion easier. You can do it from a char, but it's a little icky (well not to me because I'm a C programmer at heart).

If you want the second to last:

if (number.length() >= 2) {
    int myNumber = number.charAt(number.length() - 2) - '0';
}

Or for your loop:

for (int i = number.length()-2; i>-1; i-=2)
    int x = number.charAt(i) - '0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM