Why is my serial number system repeating the number 001? - java

I'm trying to assign a unique ID to my contacts list in Java. It works fine except for the first number. It always repeats ID001 twice before moving on to ID002. Any Idea why?
private static String getSN() {
String SN = "ID001";
for (int i = 0; i < AddressBook.size(); i++) {
if(AddressBook.size()<10){
if (AddressBook.get(i).substring(0, 4).contains("ID00"+i));
int snString = i+1;
SN = "ID00"+Integer.toString(snString);
if(SN.equals("ID0010")){
SN = ("ID010");
}
}
else{
if(AddressBook.size()<100){
if (AddressBook.get(i).substring(0, 5).equals("ID0"+i));
int snString = i+1;
SN = "ID0"+Integer.toString(snString);
if(SN.equals("ID00100")){
SN = ("ID0100");
}
}
}
}
return SN;
}

Why is my serial number system repeating the number 001?
Because SN is a local variable. A local variable in a static method is still a local variable, and it disappears each time a call to the method returns.
You probably should be using a static field ... declared in the enclosing class.

I figured out a much simpler way to do things. Instead of using a loop, every time I add a new person to my contact list I will ad a serial number.
private static void setSN() {
if (AddressBook.size() < 10) {
for (int i = 0; i < AddressBook.size(); i++) {
String tempString = AddressBook.get(i);
if (tempString.contains("ID00" + Integer.toString(AddressBook.size() + 1))) {
SN = "ID00" + Integer.toString(AddressBook.size() + 2);
}
else{
SN = "ID00" + Integer.toString(AddressBook.size() + 1);
}
}
}
else {
if (AddressBook.size() < 100) {
for (int i = 0; i < AddressBook.size(); i++) {
String tempString = AddressBook.get(i);
if (tempString.contains("ID0" + Integer.toString(AddressBook.size() + 1))) {
SN = "ID0" + Integer.toString(AddressBook.size() + 2);
}
else{
SN = "ID0" + Integer.toString(AddressBook.size() + 1);
}
}
}
}
}

Try this:
1. Modify AddressBook.get(i).substring(0, 4).contains("ID00"+i) by
AddressBook.get(i).substring(0, 5).contains("ID00"+(i+1))
2. Modify int snString = i+1; by
int snString = i+2;
3. This is because the index of the list starts at 0.
private static String getSN() {
String SN = "ID001";
for (int i = 0; i < AddressBook.size(); i++) {
if(AddressBook.size()<10){
if (AddressBook.get(i).substring(0, 5).contains("ID00"+(i+1))){
int snString = i+2;
SN = "ID00"+Integer.toString(snString);
}
if(SN.equals("ID0010")){
SN = ("ID010");
}
} else {
if(AddressBook.size()<100){
if (AddressBook.get(i).substring(0, 5).equals("ID0"+(i+1))) {
int snString = i+2;
SN = "ID0"+Integer.toString(snString);
}
if(SN.equals("ID00100")){
SN = ("ID0100");
}
}
}
}
return SN;
}

Related

Add Two Polynomials Java Program

I am working on this simple program that adds two polynomials. However, I am getting wrong results and could not spot the mistake.
import java.util.LinkedList;
public class Polynomial {
private LinkedList<Term> terms = new LinkedList<Term>();
private class Term {
private int coef;
private int exp;
public Term(int coef, int exp) {
this.coef = coef;
this.exp = exp;
}
public int getCoef() {
return coef;
}
public int getExp() {
return exp;
}
public String toString() {
return (this.coef + "x^" + this.exp);
}
}
public String addPoly(String first, String second) {
LinkedList<Term> otherTerms = new LinkedList<Term>();
String result = "";
String [] termsArray1 = first.split(";");
String [] termsArray2 = second.split(";");
for (int i = 0; i < termsArray1.length; i++) {
String [] temp = termsArray1[i].split("x\\^");
int currentCoef = Integer.parseInt(temp[0]);
int currentExp = Integer.parseInt(temp[1]);
Term currentTerm = new Term(currentCoef, currentExp);
terms.add(currentTerm);
}
for (int i = 0; i < termsArray2.length; i++) {
String [] temp = termsArray2[i].split("x\\^");
int currentCoef = Integer.parseInt(temp[0]);
int currentExp = Integer.parseInt(temp[1]);
Term currentTerm = new Term(currentCoef, currentExp);
otherTerms.add(currentTerm);
}
int i = 0;
int j = 0;
while (true){
if(i == terms.size() || j == otherTerms.size()) {
break;
}
if(terms.get(i).getExp() < otherTerms.get(j).getExp()) {
result += (otherTerms.get(j).toString() + ";");
j++;
}
if(terms.get(i).getExp() > otherTerms.get(j).getExp()) {
result += (terms.get(i).toString() + ";");
i++;
}
if(terms.get(i).getExp() == otherTerms.get(j).getExp()) {
Term temp = new Term((terms.get(i).getCoef() + otherTerms.get(j).getCoef()), terms.get(i).getExp());
result += (temp.toString() + ";");
i++;
j++;
}
}
result = result.substring(0, result.length()-1);
return result;
}
}
::Test::
String s3 = "5x^2;-4x^1;3x^0";
String s4 = "6x^4;-1x^3;3x^2";
Polynomial p = new Polynomial();
System.out.println(p.addPoly(s4, s3));
Expected result: 6x^4;-1x^3;7x^2;-4x^1;3x^0
Actual result: 3x^4;7x^2;-1x^1;10x^0
The problem is that when your loop exits, one of the following can still be true:
i < terms.size()
j < j == otherTerms.size()
And this is the case with your example input. This means that part of one of the terms has not been processed and integrated into the output.
A second problem is that your multiple if statements are not exclusive; after the first if block is executed and j++ has executed, it might well be that j is an invalid index in otherTerms when the second if is evaluated. This should be avoided by turning the second and third if into else if.
Here is a fix for that loop:
while (i < terms.size() || j < otherTerms.size()) {
if(i == terms.size() || j < otherTerms.size() && terms.get(i).getExp() < otherTerms.get(j).getExp()) {
result += (otherTerms.get(j).toString() + ";");
j++;
}
else if(j == otherTerms.size() || i < terms.size() && terms.get(i).getExp() > otherTerms.get(j).getExp()) {
result += (terms.get(i).toString() + ";");
i++;
}
else if(terms.get(i).getExp() == otherTerms.get(j).getExp()) {
Term temp = new Term((terms.get(i).getCoef() + otherTerms.get(j).getCoef()), terms.get(i).getExp());
result += (temp.toString() + ";");
i++;
j++;
}
}
Better approach
Your approach is not really OOP. Ideally, the first expression should serve to create one instance of Polynomial and the other expression should serve to create another instance of Polynomial. Then there should be a method that can add another Polynomial instance to the own instance. Finally there should be a toString method that returns the instance as a string in the required format. Your driver code would then look like this:
Polynomial a = new Polynomial("5x^2;-4x^1;3x^0");
Polynomial b = new Polynomial("6x^4;-1x^3;3x^2");
Polynomial sum = a.addPoly(b);
System.out.println(sum.toString());
This is much more object oriented, and will automatically avoid the code repetition that you currently have.

Separate text in k-shingles without Scanner.class in Java

I am trying to separate a text in k-shingles, sadly I cannot use scanner. If the last shingle is too short, I want to fill up with "_". I came this far:
public class Projektarbeit {
public static void main(String[] args) {
testKShingling(7, "ddssggeezzfff");
}
public static void testKShingling(int k, String source) {
//first eliminate whitespace and then fill up with withespaces to match target.length%shingle.length() == 0
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<String>();
int i;
int l = txt.length();
String shingle = "";
if (k == 1) {
for(i = 0; i < l; i++){
shingle = txt.substring(i, i + k);
shingles.add(shingle);
};
}
else {
for(i = 0; i < l; i += k - 1){
try {
shingle = txt.substring(i, i + k);
shingles.add(shingle);
}
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
};
};
}
System.out.println(shingles);
}
}
Output: [ddssgge, eezzfff, f______]
It works almost, but in the with the given parameters in the example the last shingle is not necessary (it should be [ddssgge, eezzfff]
Any idea how to do this more beautiful?
To make the code posted work you only need to add break and the end of the catch block:
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
break;
};
Having said that I wouldn't use an Exception to control the program. Exception are just that: should be used for run time errors.
Avoid StringIndexOutOfBoundsException by controlling the loop parameters:
public static void main(String[] args) {
testKShingling(3, "ddssggeezzfff");
}
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<>();
int stringLength = txt.length();
if (substringLength == 1) {
for(int index = 0; index < stringLength; index++){
String shingle = txt.substring(index, index + substringLength);
shingles.add(shingle);
};
}
else {
for(int index = 0; index < stringLength -1 ; index += substringLength - 1){
int endIndex = Math.min(index + substringLength, stringLength);
String shingle = txt.substring(index, endIndex);
if(shingle.length() < substringLength){
shingle = extend(shingle, substringLength);
}
shingles.add(shingle);
};
}
System.out.println(shingles);
}
private static String extend(String shingle, int toLength) {
String s = shingle;
for(int index = 0; index < toLength - shingle.length(); index ++){
s = s.concat("_");
}
return s;
}
An alternative implementation of testKShingling:
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
ArrayList<String> shingles = new ArrayList<>();
if (substringLength == 1) {
for(char c : txt.toCharArray()){
shingles.add(Character.toString(c));
};
}
else {
while(txt.length() > substringLength) {
String shingle = txt.substring(0, substringLength);
shingles.add(shingle);
txt = txt.substring(substringLength - 1); //remove first substringLength - 1 chars
}
if(txt.length() < substringLength){ //check the length of what's left
txt = extend(txt, substringLength);
}
shingles.add(txt); //add what's left
}
System.out.println(shingles);
}

Arrange the numbers by subtracting

I have a java problem that I don't know how to solve the program is :
two number must got from user n,k.
I need to find a permuation of numbers from 1 to N such that the difference between two items >=k for example :
we get the numbers (n = 5 and k = 2 )
and the answer must be 1,4,2,5,3 :
and for (n=2 and k = 2) there is not answer because the difference between 1 and two is 1(1,2 or 2,1).
I hope you understand what I want.
and I write some codes that are wrong:
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int n = user_input.nextInt();
int k = user_input.nextInt();
int a ;
if (n%2==0) a = (n-2)/2; else a = (n-1)/2 ;
if (k!=a) {System.out.println("Impossible"); return;}
int h = k+1;
int value = 0;
int t = 1;
boolean b = true;
String res = "1 ";
while (value<n-1) {
value++;
if (b){
t = t + h;
res = res + t + " ";
b = false;
}else {
t = t-k;
res = res + t + " ";
b = true;
}
}
System.out.println(res);
}
Here is the code
public class HelloWorld{
public static void calculationMethod(int n, int k) {
if(n<2 || n/2 < k) {
System.out.println("Impossible");
return;
}
else {
int i = (int)Math.ceil(n/2.0);
int j = n;
int start = i;
boolean flag = true;
while(i>=1 || j>start) {
if(flag) {
System.out.print(i + " " );
i--;
flag = false;
}
else {
System.out.print(j + " " );
j--;
flag = true;
}
}
}
}
public static void main(String []args){
calculationMethod(7,3);
}
}
The idea is to divide your range(n) in half. If k>n/2 then it is not possible to construct any such sequence.
If that is not the case, then have 2 pointers one at the middle of your range and one at the end of the range. and print them alternatively decrementing both pointers until u reach the beginning.
Feel free to improve the code.
public void calculationMethod(int n, int k) {
ArrayList<Integer> intList = new ArrayList<>();
for (int i = 1; i <= n; i++) {
int a = i;
int b = i + 2;
if (!intList.contains(a) && a<=n) {
intList.add(a);
}
if (!intList.contains(b) && b<=n) {
intList.add(b);
}
}
String mValues= TextUtils.join(",",intList);
Log.i("values", mValues);
}

java sort string array according to kurdish characters

Is there any short way to sort a string array by Kurdish characters? I've looked at some source on internet but I couldn't find any solution. There is a way to sort. Writing a code alike a novel but it is a very long work.
kurdish characters: a,b,c,ç,d,e,ê,f,g,h,i,î,j,k,l,m,n,o,p,q,r,s,ş,t,û,u,v,w,x,y,z
The Collator class should come in-handy here. To quote from the doc,
The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.
So try something like this:
Collator unicodeCollator = Collator.getInstance(Locale.UNICODE_LOCALE_EXTENSION);
Collections.sort(yourListOfCharacters, unicodeCollator);
Note that we are able to call java.util.Collections.sort directly as above, because Collator implements the Comparator interface.
If for whatever reasons Locale.UNICODE_LOCALE_EXTENSION doesn't work, here's the full list of supported locales. And you can create your own locale using the Locale constructor.
I've solved my problem: content of my file was like this:
*Nîzamettîn Ariç - Kardeş Türküler - Rojek Tê
Bê xem bê şer welat azad rojek tê
Rojek ronahî rojek bişahî rojek tê
Roj Roja me ye....
*Koma Çiya - Tolhildan ^ Daketine Meydanê
Daketine meydanê gerilayên dînemêr
Ji bona tolhildanê wek baz û piling û şêr...
My solution: thîs letters is proper for toLowerCase function:
ABCÇDEÊFGĞHİÎJKLMNOÖPQRSŞTÛUÜVWXYZ
just I was problem. because lowerCase(I) for turkish is ı; but for kurdish it is i.
code:
in onCreate():
...
alfabetBike();
...
public static void alfabetBike() {
for (int i = 0; i < tips.length(); i++) {
String[] derbasi_arr = sernavs[i];
String[] derbasi_got = gotins[i];
for (int j = 0; j < hejmar[i] - 1; j++) {
int indeks = j;
String yaMezin = derbasi_arr[j];
for (int k = j + 1; k < hejmar[i]; k++) {
if (compareTwoString(yaMezin.substring(1), derbasi_arr[k].substring(1)) > 1) {
yaMezin = derbasi_arr[k];
indeks = k;
}
}
if (indeks != j) {
derbasi_arr[indeks] = derbasi_arr[j];
String derbasi = derbasi_got[indeks];
derbasi_got[indeks] = derbasi_got[j];
derbasi_arr[j] = yaMezin;
derbasi_got[j] = derbasi;
}
}
gotins[i] = derbasi_got;
sernavs[i] = derbasi_arr;
}
}
private static void printFile(){
alfabetBike();
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/alfabetfolder");
dir.mkdirs();
File file = new File(dir, "alfabet_title.txt");
File file2 = new File(dir, "alfabet.txt");
try {
FileOutputStream f = new FileOutputStream(file,false);
PrintWriter pw = new PrintWriter(f);
FileOutputStream f2 = new FileOutputStream(file2,false);
PrintWriter pw2 = new PrintWriter(f2);
for (int i = 0; i < tips.length(); i++) {
for (int j = 0; j < hejmar[i]; j++) {
Log.d("ssdddddd", "add" + hejmar[i] + "-" + j + " " + sernavs[i][j].trim());
pw.println(sernavs[i][j]);
pw.flush();
pw2.println(sernavs[i][j] + "\n" + gotins[i][j].trim());
pw2.flush();
}
}
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("erroooor", "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
}
public static int compareTwoString(String yek, String du) {
String d1 = yek, d2 = du;
d1 = strLower(d1, d1.charAt(0));
d2 = strLower(d2, d2.charAt(0));
int length, yaDirej;
if (yek.length() > du.length()) {
yaDirej = 1;
length = yek.length();
} else if (yek.length() < du.length()) {
yaDirej = 2;
length = du.length();
} else {
yaDirej = 0;
length = yek.length();
}
for (int i = 0; i < length; i++) {
int id1 = -1, id2 = -1;
if (i == d1.length() || i == du.length()) {
return yaDirej;
}
for (int j = 0; j < tips.length(); j++) {
if (d1.charAt(i) == tips.charAt(j)) id1 = j;
if (d2.charAt(i) == tips.charAt(j)) id2 = j;
}
if (id1 > id2)
return 2;
else if (id2 > id1)
return 1;
else
continue;
}
return 0;
}
public static String strLower(String str, char ziman){
final StringBuilder mutable = new StringBuilder(str);
final StringBuilder yedek = new StringBuilder(str.toLowerCase());
for (int i = 0; i < str.length(); i++) {
if (ziman == '?' && mutable.charAt(i) == 'I')
mutable.setCharAt(i, 'i');
else if (ziman == '*' && mutable.charAt(i) == 'I')
mutable.setCharAt(i, 'ı');
else mutable.setCharAt(i,yedek.charAt(i));
}
return mutable.toString();
}
edit:
in AndroidManifest.xml
<manifest...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
....
</manifest...>
You can build your own comparison so that, no matter what characters you are dealing with, it is going to sort the way you want. As you can see from the following code, I have set the comparison value by counting from a-z so that a=0, b=1...etc Then, I used the bubble sort strategy, which is basically switching the smallest elements continuously to the left and shifting others to the right.
public class Sort {
public static String compare(String compare1, String compare2) {
for (int i = 0; i < compare1.length(); i++) {
if (letterValue(compare1, i) < letterValue(compare2, i)) {
return compare1;
} else if (letterValue(compare1, i) > letterValue(compare2, i)) {
return compare2;
} else if (letterValue(compare1, i) == -1 || letterValue(compare2, i) == -1) {
System.out.print("Some letters are not within the alphabet!");
}
}
return compare1;
}
public static boolean smaller(String compare1, String compare2) {
if (compare(compare1, compare2).equalsIgnoreCase(compare1)) {
return true;
} else {
return false;
}
}
public static int letterValue(String input, int letterPosition) {
String order = "abcçdeêfghiîjklmnopqrsştûuvwxyz";
int value = -1;
for (int i = 0; i < order.length(); i++) {
if (input.toLowerCase().charAt(letterPosition) == order.charAt(i)) {
value = i;
}
}
return value;
}
public static void main(String[] args) {
String[] input = {"BARÊZ", "ÇÊneR", "ASTÛ", "badîn", "BADÎN"};
String swap;
int i, d;
for (i = 0; i < (input.length - 1); i++) {
for (d = 0; d < input.length - i - 1; d++) {
if (!smaller(input[d], input[d + 1])) {
swap = input[d];
input[d] = input[d + 1];
input[d + 1] = swap;
}
}
}
System.out.println("Sorted list: ");
for (i = 0; i < input.length; i++) {
System.out.print(input[i] + " ");
}
}
}
Output
Sorted list:
ASTÛ badîn BADÎN BARÊZ ÇÊneR

Java code with tests - infinite loop?

I try to get the relationship between people. However, when I run unit test, the test runs forever, it doesn't get the result and my CPU usage was high.
Could someone see what's wrong with my code?
The string relations are multiple line inputs of string with in the format of "A , B C , D" where A is the parent of B and C is the parent of D.
This is the default constructor for the code and the input in string format. We don't need to check if the format is correct:
public SeeRelations(String relations){
this.relations = relations;
}
This the helper function to get each line of the string from the formatted input:
//helper function to get each line of the string
private ArrayList<String> lineRelations(){
int i;
ArrayList<String> lineRelations = new ArrayList<String>();
String[] lines = relations.split("\n");
for(i = 0; i < lines.length; i++){
lineRelations.add(lines[i]);
}
return lineRelations;
}
This is the function to put all the relations from the input formatted string to arraylists:
//helper function to put each of the relationship in arraylists
private ArrayList<ArrayList<String>> allRelations(){
int i;
ArrayList<ArrayList<String>> allRelations = new ArrayList<ArrayList<String>>();
ArrayList<String> lineRelations = lineRelations();
for(i = 0; i < lineRelations.size(); i++){
ArrayList<String> eachLine = new ArrayList<String>(Arrays.asList(lineRelations.get(i).split("\\s*,\\s*")));
allRelations.add(eachLine);
}
return allRelations;
}
This is the method to check if the input name exists:
//helper function to see if the name exist for seeRelations()
private boolean hasThisName(String name){
ArrayList<ArrayList<String>> allRelations = allRelations();
int i;
int j;
for(i = 0; i < allRelations.size(); i++){
for(j = 0; j < allRelations.get(i).size(); j++){
if(name.equals(allRelations.get(i).get(j))){
return true;
}
}
}
return false;
}
This is the function to get the generation number between two people:
//helper function to get Generation number of seeRelations()
private int getGenerationNum(String person, String ancestor){
ArrayList<ArrayList<String>> allRelations = allRelations();
String name;
int i;
int j;
int generationNum = 0;
for(i = 0, j = 0, name = ancestor; i < allRelations.size(); i++){
if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
generationNum++;
ancestor = allRelations.get(i).get(1);
i = 0;
j = 1;
}
else if(ancestor.equals(allRelations.get(i).get(0)) && person.equals(allRelations.get(i).get(1))){
generationNum++;
j = 1;
break;
}
}
if(j == 0){
return 0;
}
else{
return generationNum;
}
}
This is the method to get multiple of "great" for the final output:
private String great(int num){
int i;
String great = "";
for(i = 0; i < num; i++){
great += "great";
}
return great;
}
This is my final method to check the relationship between two people:
public String SeeRelations(String person, String ancestor){
int generationNum = getGenerationNum(person, ancestor);
String great = great(generationNum - 2);
if(!(hasThisName(person) && hasThisName(ancestor))){
return null;
}
else{
if(generationNum == 0){
return null;
}
else if(generationNum == 1){
return ancestor + " is the parent of " + person;
}
else if(generationNum == 2){
return ancestor + " is the grandparent of " + person;
}
else{
return ancestor + " is the" + " " + great +"grandparent of " + person;
}
}
}
This is my test cases, And it runs forever and couldn't get a result
public class FamilyTreeTest {
#Test
public void testSeeRelations() {
FamilyTree relation2 = new FamilyTree("John Doe , Mary Smith" + "\n" + "Martin Weasel , John Doe");
assertEquals("Martin Weasel is the grandparent of Mary Smith", familyTree2.SeeRelations("Mary Smith", "Martin Weasel"));
}
for(i = 0, j = 0, name = ancestor; i < allRelations.size(); i++){
if(name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))){
generationNum++;
ancestor = allRelations.get(i).get(1);
i = 0;
j = 1;
}
else if(ancestor.equals(allRelations.get(i).get(0)) && person.equals(allRelations.get(i).get(1))){
generationNum++;
j = 1;
break;
}
}
here you have your faulty lines
in your case your ancestor/name is "Martin Weasel" given relation for martin is "John Doe", but you are looking for mary smith so name.equals(allRelations.get(i).get(0)) && !person.equals(allRelations.get(i).get(1))) this is true and this i = 0; makes your loop starts from beginning
what you could do, try to create object person
ie
class Person{
String name;
List childrens;
List parents;
...
}
then just do simple tree walker
int SearchDown(Person person, String searchedRelation,int generation)
{
if person.getName().equals(searchedRelation())
return generation;
for (Person child: person.getChildren())
{
int generation = SearchDown(child, searchedRelation, generation+1);
if (generation!=-1) return generation;
}
return -1;
}
etc...
i'm really finding this way much easier to deal with all types of trees

Categories

Resources