I am trying to make a program that counts significant figures and I am almost done there is one last thing that I am completely stuck on I can't figure out how to count the zeros between the non zero numbers here is my code:
public class Main {
public static void main(String[] args) {
String Integer = "10010000000";
String Substring = null;
String SubString2 = null;
if(Integer.contains(".")){
Substring = Integer.substring(0,Integer.indexOf("."));
System.out.println(Substring);
SubString2 = Integer.substring(Integer.indexOf(".")+1,Integer.length());
System.out.println(SubString2);
}
char [] array = Integer.toCharArray();
char [] array1 = null;
if(Substring !=null)
array1 = Substring.toCharArray();
char [] array2 = null;
if(SubString2!=null)
array2 = SubString2.toCharArray();
System.out.println(amountofSigFigs(array,array1,array2,Integer));
}
public static int amountofSigFigs(char [] a,char [] a1,char [] a2,String Integer){
int count = 0;
if(a1==null && a2 == null){
for(int i = 0;i<a.length;i++){
if(!(a[i]=='0')){
count++;
}
}
}
else{
for(int i = 0;i<a1.length;i++){
if(!(a[i]=='0')){
count++;
}
}
for(int i = 0;i<a2.length;i++){
count++;
}
}
return count;
}
}
You shouldn't use keywords such as "Integer" for variable identifiers.
There are some lingering questions I have, but I would simply use Java's builtin split() function on strings and use regex to split the string into significant figures (ignoring ending and leading zeroes). Then return the sum of the length of the strings . Here is the code for pure integers.
If we include floats, there are other rules you would have to consider, such as zeroes after a decimal point count except if they are preceded by all zeroes (3.00 has 3, 0.03 has 1). In this case, the regex regrettably becomes much more contrived, but I would use something like
"(^0+(\\.?)0*|(~\\.)0+$|\\.)"
to split on. See code below (Note -- still works on integers)Here's a quick look into the regex:
^0+(\\.?)0*
means one or more leading zeroes (0+
) followed optionally by a decimal (\\.?
) and then zero or more zeroes (0*
).(~\\.)0+$
means we want to take off ending zeroes (0+$
), but only if they aren't preceded by a decimal ((~\\.)
).\\.
means split whatever is left by the decimal point.