Generate random numbers less than 9 - android

I want to generate random number in two field between range 1-8 and also field sum should be less than 9.
what I've done done till now
for (int i; i <= 6; i++) {
fieldOne = rand.nextInt(9 - 5) + 5;
fieldTwo = rand.nextInt(9 - 5) + 5;
fieldSum = fieldOne + fieldTwo;
System.out.print(fieldSum); // should be < 9 and not repetition
}
but fieldSum become greater then 9 so How it is control this condition?
And Sequence should be random should not repeat 2 or more time.

rand.nextInt(9-5) won't calculate a random number between 5 and 8, it will make the operation 9 minus 5 and then will calculate rand.nextInt(4).
To calculate a random number between 5 and 8 you have to do something like this:
Random r = new Random();
for (int i = 0; i < 10; i++) {
int rand1 = r.nextInt(4) + 5;
int rand2 = r.nextInt(4) + 5;
int result = rand1 + rand2;
Log.v("", "" + result);
}
The problem is that result can't be < than 9 because you are summing two numbers that are => 5 so the lower result you can get is 10.
Edit for a solution with no repetition:
private List<Integer> rdmNumList = new ArrayList<Integer>();
private final int leftLimitRange = 1;
private final int rightLimitRange = 10;
private final int numOfIteration = 10;
public void generateNumList() {
for (int i = leftLimitRange; i <= rightLimitRange; i++) {
this.rdmNumList.add(num);
}
}
public int getRandomNumer() {
Random r = new Random();
int rNum = r.nextInt(rdmNumList.size());
int result = this.rdmNumList.get(rNum);
this.rdmNumList.remove(rNum);
return result;
}
public void test() {
this.generateNumList();
if(this.numOfIteration <= ((this.rightLimitRange - this.leftLimitRange + 1))) {
for (int i = 0; i < this.numOfIteration; i++) {
Log.v("Debug Output", String.valueOf(this.getRandomNumer()));
}
}
}
Note: this is efficient only with small range of number
This code works but it's far from being good. You should find some other solution by yourself. This answer will help you find your way

Maybe try this --> random.nextInt()%9; another way Get random nuber with random.nextInt(9).

Try,
fieldSum=(fieldOne+fieldTwo)%9;
This will def

Related

MPAndroidChart stacked bar chart shows wrong/duplicated values

I'm trying to build a bar chart to show daily data of the week using MPAndroidChart. the data is shown localized so they're arranged depending on the first day of the week (Monday or Sunday). Some data get duplicated and added to several bars and some are show in wrong bars. I've been trying to solve this for a week and had no luck.
This is how I process data:
List<String> dailyIncomes = new ArrayList<>(7);
List<String> dailyExpenses = new ArrayList<>(7);
for (int x = 0; x < 7; x++) {
dailyIncomes.add("0");
dailyExpenses.add("0");
}
for (int i = 0; i < transactionsList.size(); i++) {
TransactionItem currentTransaction = transactionsList.get(i);
DateTimeHandler dateTimeHandler = new DateTimeHandler(currentTransaction.getUserDate()); //my own class to get day, week or year
int transactionYear = dateTimeHandler.getYear();
int transactionWeek = dateTimeHandler.getWeekOfYear();
int transactionDay = dateTimeHandler.getDayOfWeek();
if (transactionWeek == week && transactionYear == year) {
for (int d = 0; d < 7; d++) {
if (d + 1 == transactionDay) {
if (weekFields.getFirstDayOfWeek().getValue() == 7) {
if (transactionDay == 7) {
if (currentTransaction.getPrefix().equals("+")) {
double dailyTotal = Double.parseDouble(dailyIncomes.get(0)) + currentTransaction.getAmountValue();
dailyIncomes.add(0, "" + dailyTotal);
} else {
double dailyTotal = Double.parseDouble(dailyExpenses.get(0)) + currentTransaction.getAmountValue();
dailyExpenses.add(0, "" + dailyTotal);
}
} else {
if (currentTransaction.getPrefix().equals("+")) {
double dailyTotal = Double.parseDouble(dailyIncomes.get(d + 1)) + currentTransaction.getAmountValue();
dailyIncomes.add(d + 1, "" + dailyTotal);
} else {
double dailyTotal = Double.parseDouble(dailyExpenses.get(d + 1)) + currentTransaction.getAmountValue();
dailyExpenses.add(d + 1, "" + dailyTotal);
}
}
} else {
if (currentTransaction.getPrefix().equals("+")) {
double dailyTotal = Double.parseDouble(dailyIncomes.get(d)) + currentTransaction.getAmountValue();
dailyIncomes.add(d, "" + dailyTotal);
} else {
double dailyTotal = Double.parseDouble(dailyExpenses.get(d)) + currentTransaction.getAmountValue();
dailyExpenses.add(d, "" + dailyTotal);
}
}
}
}
}
}
WeeklyReport weeklyReport = new WeeklyReport(.....,dailyIncomes, dailyExpenses,....);
//to load next cards
weekCount++;
if (this.week == 1) {
yearCount++;
this.year = this.year - yearCount;
}
this.week = LocalDate.now()
.minusYears(yearCount)
.minusWeeks(weekCount)
.get(weekFields.weekOfWeekBasedYear());
weeklyReportList.add(weeklyReport);
adapter.submitList(weeklyReportList);
adapter.notifyItemInserted(adapter.getItemCount() + 1);
How I set data to the chart:
List<BarEntry> dailyDetails = new ArrayList<>();
for (int i = 0; i < 7; i++)
dailyDetails.add(new BarEntry(
(float) i, new float[]{
Float.parseFloat(weeklyReport.getDailyIncomes().get(i)),
Float.parseFloat(weeklyReport.getDailyExpenses().get(i))
}));
BarDataSet dailyDetailsSet = new BarDataSet(dailyDetails, "");
String[] labels = {context.getString(R.string.incomes), context.getString(R.string.expenses)};
//add x axis labels (days of week)
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int firstDay = weekFields.getFirstDayOfWeek().getValue();
Log.i(TAG, "first day: " + firstDay);
final List<String> xLabels = new ArrayList<>();
for (int x = 0; x < 7; x++)
xLabels.add("DAY");
if (firstDay == 7) {
xLabels.add(0, LocalDate.now().with(DayOfWeek.of(7)).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
for (int z = 1; z < 7; z++)
xLabels.add(z, LocalDate.now().with(DayOfWeek.of(z)).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
} else
for (int y = 0; y < 7; y++)
xLabels.add(LocalDate.now().with(DayOfWeek.of(y + 1)).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
dailyDetailsSet.setStackLabels(labels);
BarData data = new BarData(dailyDetailsSet);
chartView.setData(data);
chartView.getXAxis().setValueFormatter(new IndexAxisValueFormatter() {
#Override
public String getFormattedValue(float value) {
return xLabels.get((int) value);
}
});
chartView.invalidate();
The chart looks like this:
I already tried using switch statements instead of loops but no luck. I'm sure that the data is accurate because there are some other charts like budget and monthly reports and nothing's wrong with them. It must be some silly mistake and I've been trying to fix this for three days but there's always something wrong.
Could someone help me and point out what I'm doing wrong? I'd appreciate it so much. Thanks. (Sorry if there's bad English)
Please ask me if you need to see more of the code.

Android, Random do not repeat same number twice in a row

I need to fill a vector with integers, but I have some troubles, I need to fill it with random numbers, but not two numbers in a row. (ex. not like this: 1,4,4,3,5,9)
I made this code but it does not work well :
# first time loja=1;
but until the game : loja++;
int[] con;
Random Method :
private int nasiqim (int max){
Random nasiqimi = new Random();
int i = 0;
i=nasiqimi.nextInt(max);
return i;
}
Working Code :
int i;
con = new int [loja];
for (i=0; i<loja; i++)
{
con[i] = nasiqim(8);
if(i>0){
while(con[i]==con[i-1])
{
con[i] =nasiqim(8);
}
}
i++;
}
The results are like this:
1
1,4
1,4,1
1,4,1,4
1,4,1,4,1
5,3,5,3,5,3
5,3,5,3,5,3,5
And this is not what I need, I need the numbers to really random, not like this,
Will be great if list will be like this something : 1,5,6,7,3,0,2,4,1,0,2,3...
Thank you!!
private int[] con = null;
private final Random nasiqimi = new Random();
/**
* Test run random.
*/
#Test
public void testRunRandom() {
int loja = 10;
con = new int[loja];
for (int i = 0; i < loja; i++) {
int nextRandom = 0;
while (true) {
nextRandom = nasiqim(8);
if (i == 0 || con[i - 1] != nextRandom) {
con[i] = nextRandom;
break;
}
}
}
}
/**
* Gets the random.
*
* #param max the max
* #return the random
*/
private int nasiqim(int max) {
return nasiqimi.nextInt(max);
}
I've created a sample class
import java.util.*;
public class Foo {
static Random r = new Random();
static int[] con;
static int loja = 8;
private static int randomInt(int max) {
return r.nextInt(max);
}
public static void main(String args[]) {
int i;
con = new int[loja];
for (i = 0; i < loja; i++) {
con[i] = randomInt(8);
if (i > 0) {
while (con[i] == con[i - 1]) {
con[i] = randomInt(8);
}
}
}
System.out.println( Arrays.toString(con));
}
}
All variables are static, notice I get rid of the i++; increment at the end of the for loop.

decimal to ascii android

I am attempting to implement a conversion from a decimal number to ascii. Right now, i've hard coded it to 50 but I will use userinput later on. When I run the application and call the method, what is outputed is random (it changes everytime I press it) eg "[C#4263f600"
I followed the process in the link: decimal to binary. Why am I getting such a weird output?
//method
if (valid) {
String str = ascii();
mTextOutput.setText(str);
...
public String ascii(){
char[] binary_reverse = new char[9];
char[] binary = new char[9];
int ascii = 50;
int y = 0;
while (ascii !=1) {
if (ascii % 2 ==0)
{
binary_reverse[y]='0';
}
else if (ascii % 2 == 1)
{
binary_reverse[y]='1';
}
ascii /= 2;
y++;
}
if (ascii ==1)
{
binary_reverse[y] = '1';
}
if (y<8) {
for(; y < 8; y++) {
binary_reverse[y] = '0';
}
}
for (int z = 0; z < 8; z++) {
binary[z] = binary_reverse[7-1];
}
String str = binary.toString();
return str;
}
//You can try this :
binary[z] = binary_reverse[7-1]; - So you want to set every element of binary to the value in binary_reverse[6]
//and also
String str = binary.toString(); to String str = new String(binary);
reference : #Tim

FSK Demodulation Code (Android)

I am intending to perform FSK demodulation and came across the Androino Project(https://code.google.com/p/androino/source/browse/wiki/AndroinoTerminal.wiki), which reads in data from the Adruino into the phone's audio jack, which is pretty darn cool.
I am trying to go through the code but I can't make sense of some impt values. :((
Why is the bit-high = 22 peaks, bit-low = 6 peaks, private static int HIGH_BIT_N_PEAKS = 12 and private static int LOW_BIT_N_PEAKS = 7?? And why is it 136 samples per encoded bit?
Am I also right to say that the FSK rate of the Adruino is set at 315Hz?
I have attached the hardware(softTerm) codes as well: https://code.google.com/p/androino/source/browse/trunk/arduino/SoftTerm/SoftModem/SoftModem.h and the cpp file is in there as well. Dun have enough reputation points to post both links.
/** Copyright (C) 2011 Androino authors
Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.androino.ttt;
import android.util.Log;
public class FSKModule {
// Experimental results
// Arduino sends "a" character (97) 1100001
// The generated message is 0110.0001
// 136 samples per encoded bit
// total message = 166 bits: 155(high)+1(low)+8bit+stop(high)+end(high)
private static int SAMPLING_FREQUENCY = 44100; //Hz
private static double SAMPLING_TIME = 1.0/SAMPLING_FREQUENCY; //ms
// reading zero+155(high)+1(low)+8bit+stop+end+zero
private static int FREQUENCY_HIGH = 3150;
private static int FREQUENCY_LOW = 1575;
//high: 7 samples/peak
//low : 14 samples/peak
// 1492 samples/message low+8bits+stop+end
// 136 samples/bit (=1492/11)
private static int SAMPLES_PER_BIT = 136;
private static int ENCODING_SAMPLES_PER_BIT = SAMPLES_PER_BIT/2; // 68
// bit-high = 22 peaks
// bit-low = 6 peaks
private static int HIGH_BIT_N_PEAKS = 12;
private static int LOW_BIT_N_PEAKS = 7;
private static int SLOTS_PER_BIT = 4; // 4 parts: determines the size of the part analyzed to count peaks
private static int N_POINTS = SAMPLES_PER_BIT/SLOTS_PER_BIT; // 34=136/4
private static double PEAK_AMPLITUDE_TRESHOLD = 60; // significant sample (not noise)
private static int NUMBER_SAMPLES_PEAK = 4; // minimum number of significant samples to be considered a peak
private static int MINUMUM_NPEAKS = 100; // if lower it means that there is no signal/message
private static final int BIT_HIGH_SYMBOL=2;
private static final int BIT_LOW_SYMBOL=1;
private static final int BIT_NONE_SYMBOL=0;
private static final int CARRIER_MIN_HIGH_BITS=12;
private static final int SOUND_AMPLITUDE = 31000;
private static final String TAG = "FSKModule";
private FSKModule(){
}
private static void debugInfo(String message){
//System.out.println(">>" + message);
Log.w(TAG, "FSKDEC:"+ message);
}
//-----------------------------------------
// DECODING FUNCTIONS
//-----------------------------------------
public static boolean signalAvailable(double[] sound){
FSKModule m = new FSKModule();
int nPoints = N_POINTS;
int nParts = sound.length / nPoints;
int nPeaks = 0;
int startIndex = 0;
int i = 0;
do {
int endIndex = startIndex + nPoints;
int n = m.countPeaks(sound, startIndex, endIndex);
nPeaks += n;
i++;
startIndex = endIndex;
if (nPeaks > MINUMUM_NPEAKS) return true;
} while (i<nParts);
if (nPeaks >3)
debugInfo("signalAvailable() nPeaks=" + nPeaks);
return false;
}
public static int decodeSound(double[] sound){
FSKModule m = new FSKModule();
// processing sound in parts and
//Log.w(TAG, "ENTRO EN processSound");
int[] nPeaks = m.processSound(sound);
if (nPeaks.length == 0) // exit: no signal detected
return -1;
//debugInfo("decodeSound nPeaks=" + nPeaks.length);
// transform number of peaks into bits
//Log.w(TAG, "ENTRO EN parseBits");
int[] bits = m.parseBits(nPeaks);//-------------------------> OK!!
//debugInfo("decodeSound nBits=" + bits.length);
// extract message from the bit array
int message = m.decodeUniqueMessage(bits, sound, nPeaks);
debugInfo("decodeSound(): message="+message + ":" + Integer.toBinaryString(message));
return message;
}
private int decodeUniqueMessageCorrected(int[] nPeaks, int startBit){
int message = 0;
// process nPeaks starting from the end
int index = (startBit+12)*SLOTS_PER_BIT;
// find zero -> non zero transition
for (int i = 0; i < index; i++) {
int i2 = nPeaks[index-i];
int i1 = nPeaks[index-i-1];
debugInfo("zero->nonzero index=" + (index-i) + ": i2=" + i2 + ":i1=" + i1);
if ( (i1-i2)>2) {
index = index-i-1;
break;
}
}
debugInfo("zero->nonzero index=" + index);
int[] bits = new int[2+8+1+2];
for (int i = 0; i < bits.length; i++) {
int peakCounter = 0;
for (int j = 0; j < 4; j++) {
peakCounter += nPeaks[index-j];
}
debugInfo("decode corrected: peakCounter="+i + ":" + peakCounter);
if (peakCounter > 7) { //LOW_BIT_N_PEAKS)
bits[i] = BIT_LOW_SYMBOL;
}
if (peakCounter > 12) { //LOW_BIT_N_PEAKS)
bits[i] = BIT_HIGH_SYMBOL;
message += Math.pow(2, i);
}
debugInfo("bit=" + bits[i] + ":" + message);
index = index -4;
}
debugInfo("decode corrected: message="+message + ":" + Integer.toBinaryString(message));
message = 0;
for (int i = 2; i < 10; i++) {
if ( bits[i] == BIT_HIGH_SYMBOL) {
message+= Math.pow(2, 7-(i-2));
}
}
return message;
}
private int decodeUniqueMessage(int[] bits, double[] sound, int[] nPeaks){
// start bit
int index = findStartBit(bits, 0);
debugInfo("decodeUniqueMessage():start bit=" + index);
if (index == -1) return -1; // no start-bit detected
if (index + 8 + 2 > bits.length)
throw new AndroinoException("Message cutted, start bit at " + index, AndroinoException.TYPE_FSK_DECODING_ERROR);
// debugging information
int number = 16; // n bits to debug
for (int i = index-5; i < index-5+number; i++) {
debugInfo("decodeUniqueMessage(): bits=" + i +":" + bits[i] );
}
for (int i = 0; i < number*SLOTS_PER_BIT; i++) {
int position = i + (index-5)*SLOTS_PER_BIT ;
debugInfo("decodeUniqueMessage(): npeaks=" + position+ ":" + nPeaks[position] );
}
// 8bits message
int value = 0;
for (int i = 0; i < 8; i++) {
int bit = bits[index+i];
if (bit==BIT_HIGH_SYMBOL) value+=Math.pow(2, i);
}
// stop bit: do nothing
// end bit: do nothing
debugInfo("MESSAGE =" + Integer.toBinaryString(value) + ":" + value);
*/
int correctedMessage = decodeUniqueMessageCorrected(nPeaks,index);
debugInfo("MESSAGE corrected=" + Integer.toBinaryString(correctedMessage) + ":" + correctedMessage);
return correctedMessage;
}
private int findStartBit(int[] bits, int startIndex){
// find carrier and start bit
int index = startIndex;
int highCounter = 0;
boolean startBitDetected = false;
do {
int bit = bits[index];
switch (bit) {
case BIT_HIGH_SYMBOL:
highCounter++; // carrier high bit
break;
case BIT_LOW_SYMBOL:
if (highCounter>CARRIER_MIN_HIGH_BITS) { // start-bit detected
startBitDetected = true;
}
else highCounter = 0; // reset carrier counter
break;
case BIT_NONE_SYMBOL:
highCounter = 0;// reset carrier counter
break;
}
index++;
if (index>=bits.length) return -1;
} while (!startBitDetected);
return index;
}
private int[] parseBits(int[] peaks){
// from the number of peaks array decode into an array of bits (2=bit-1, 1=bit-0, 0=no bit)
//
int i =0;
int lowCounter = 0;
int highCounter = 0;
int nBits = peaks.length /SLOTS_PER_BIT;
int[] bits = new int[nBits];
//i = findNextZero(peaks,i); // do not search for silence
i = findNextNonZero(peaks,i);
int nonZeroIndex = i;
if (i+ SLOTS_PER_BIT >= peaks.length) //non-zero not found
return bits;
do {
//int nPeaks = peaks[i]+peaks[i+1]+peaks[i+2]+peaks[i+3];
int nPeaks = 0;
for (int j = 0; j < SLOTS_PER_BIT; j++) {
nPeaks+= peaks[i+j];
}
int position = i/SLOTS_PER_BIT;
bits[position] = BIT_NONE_SYMBOL;
debugInfo("npeaks:i=" + i + ":pos=" + position+ ": nPeaks=" + nPeaks);
if (nPeaks>= LOW_BIT_N_PEAKS) {
//Log.w(TAG, "parseBits NPEAK=" + nPeaks);
bits[position] = BIT_LOW_SYMBOL;
lowCounter++;
}
if (nPeaks>=HIGH_BIT_N_PEAKS ) {
bits[position] = BIT_HIGH_SYMBOL;
highCounter++;
}
//if (nPeaks>5) bits[position] = 1;
//if (nPeaks>12) bits[position] = 2;
i=i+SLOTS_PER_BIT;
} while (SLOTS_PER_BIT+i<peaks.length);
lowCounter = lowCounter - highCounter;
debugInfo("parseBits nonZeroIndex=" + nonZeroIndex);
debugInfo("parseBits lows=" + lowCounter);
debugInfo("parseBits highs=" + highCounter);
return bits;
}
private int findNextNonZero(int[] peaks, int startIndex){
// returns the position of the next value != 0 starting form startIndex
int index = startIndex;
int value = 1;
do {
value = peaks[index];
index++;
} while (value==0 && index<peaks.length-1);
return index-1;
}
private int[] processSound(double[] sound){
// split the sound array into slots of N_POINTS and calculate the number of peaks
int nPoints = N_POINTS;
int nParts = sound.length / nPoints;
int[] nPeaks = new int[nParts];
int startIndex = 0;
int i = 0;
int peakCounter = 0;
do {
int endIndex = startIndex + nPoints;
int n = this.countPeaks(sound, startIndex, endIndex);
nPeaks[i] = n;
peakCounter += n;
i++;
startIndex = endIndex;
} while (i<nParts);
//} while (startIndex+nPoints<sound.length);
debugInfo("processSound() peaksCounter=" + peakCounter);
if (peakCounter < MINUMUM_NPEAKS) {
nPeaks = new int[0];
}
return nPeaks;
}
private int countPeaks(double[] sound, int startIndex, int endIndex){
// count the number of peaks in the selected interval
// peak identification criteria: sign changed and several significant samples (>PEAK_AMPLITUDE_TRESHOLD)
int index = startIndex;
int signChangeCounter = 0;
int numberSamplesGreaterThresdhold = 0;
int sign = 0; // initialized at the first significant value
do {
double value = sound[index];
if (Math.abs(value)>PEAK_AMPLITUDE_TRESHOLD)
numberSamplesGreaterThresdhold++; //significant value
// sign initialization: take the sign of the first significant value
if (sign==0 & numberSamplesGreaterThresdhold>0) sign = (int) (value / Math.abs(value));
boolean signChanged = false;
if (sign <0 & value >0) signChanged = true;
if (sign >0 & value <0) signChanged = true;
if (signChanged & numberSamplesGreaterThresdhold>NUMBER_SAMPLES_PEAK){
signChangeCounter++; // count peak
sign=-1*sign; //change sign
}
index++;
//debugInfo(">>>>>>>index=" + index + " sign=" + sign + " signChangeCounter=" + signChangeCounter + " value=" + value + " numberSamplesGreaterThresdhold=" + numberSamplesGreaterThresdhold);
} while (index<endIndex);
return signChangeCounter;
}
}

TelephonyManager.getDeviceId only returns 14 digit

TelephonyManager.getDeiceId() only return 14 digits of IMEI number.
But under Setting->Phone->Status show 15 digits.
I want to get 15 digit as appear under phone settings.
The IMEI (14 digits) is complemented by a check digit. The check digit is not
part of the digits transmitted at IMEI check occasions. The Check Digit shall
avoid manual transmission errors, e.g. when customers register stolen mobiles
at the operator's customer care desk.
http://www.tele-servizi.com/Janus/texts/imei.txt
http://en.wikipedia.org/wiki/International_Mobile_Equipment_Identity
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.getDeviceId()
This is what i have done and i getting all the 15 digits may this can help u ...
Or you can manually calculate the check-sum of the 14-digit IMEI number. e.g.
private int GetCheckSumDigit(String id) {
int digit = -1;
try{
if(id.length() == 14)
{
String str = "";
char[] digits = new char[id.length()];
id.getChars(0, id.length(), digits, 0);
for(int i=0; i<digits.length; i++)
{
String ch = digits[i]+"";
if((i+1)%2==0)
{
int x = Integer.parseInt(digits[i]+"");
x *= 2;
ch = x+"";
}
str += ch;
}
digits = new char[str.length()];
str.getChars(0, str.length(), digits, 0);
int total = 0;
for(int i=0; i<str.length(); i++)
total += Integer.parseInt(digits[i]+"");
//
int count = 0;
while((total+count)%10 != 0)
count++;
digit = count;
}
}catch(Exception exx)
{
exx.printStackTrace();
}
return digit;
}
Good Luck.
Some devices don't add last digit, we need to calculate last digit instead using Luhn algorithm:
private int getImeiCheckDigit(String imei14digits) {
if (imei14digits == null || imei14digits.length() != 14) {
throw new IllegalArgumentException("IMEI should be 14 digits");
}
int[] imeiArray = new int[imei14digits.length()];
final int DIVIDER = 10;
char[] chars = imei14digits.toCharArray();
for (int i = 0; i < chars.length; i++) {
imeiArray[i] = Character.getNumericValue(chars[i]);
}
int sum = 0;
for (int i = 0; i < imeiArray.length; i++) {
if (i % 2 == 0) {
sum += imeiArray[i];
} else {
int multi = imeiArray[i] * 2;
if (multi >= DIVIDER) {
sum += multi % DIVIDER;
sum += multi / DIVIDER;
} else {
sum += multi;
}
}
}
return (DIVIDER - sum % DIVIDER) % DIVIDER;
}

Categories

Resources