gpt4 book ai didi

java - 如何从一串数字中提取单个数字?

转载 作者:行者123 更新时间:2023-12-01 05:49:03 25 4
gpt4 key购买 nike

示例:

String number = "1234567890123456";

如何将倒数第二个数字单独存储在 int 类型变量中?

详细:

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

我该怎么做?

代码如下:

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

目标是检查信用卡号是否有效(学校项目)

最佳答案

substring/charAt您想要的数字并解析它...

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

关于java - 如何从一串数字中提取单个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5162221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com