0

In my program I'm going to store user input in an array then going to check each character to see if it's a digit or dot or E or negative sign after that I'll store it in to an array called temps.

Now I have problem in my fleating method () that don't how should I make my condition for the pattern of floating number digit-digit-dot-digit-digit (e.g 12.22)

I have my work here:

public void sorting(String data) {
    String[] temps = new String[200];
    int cpos = 0;
    int tpos = 0;

    Arrays.fill(temps, null);

    if (str.isEmpty() == false) {
        char char1 = str.charAt(cpos);

        int i = 0;
        while (i < str.length()) {
            char1 = str.charAt(cpos);

            char1 = str.charAt(tpos);
            System.out.println("the current value is  " + char1 + " ");
            tpos++;

            if (Character.isDigit(char1)) {
                temps[cpos] = "Digit";
                // System.out.println(" this number is digit");
                cpos++;
            } else if (char1 == 'e' || char1 == 'E') {
                temps[cpos] = "s_notaion";
                cpos++;
            } else if (char1 == '-') {
                temps[cpos] = "negative";
                cpos++;
            } else if (char1 == '.') {
                temps[cpos] = ".";
                cpos++;
            }
            i++;
        }
    }
}

here is the method for floating number

private static boolean floating(String [] data) {
    int count =0;
    boolean correct = false;
    for (int i = 0; i < data.length; i++) {

         if (data[i]== "Digit" )
             && data[i]=="." && data[i]"Digit"){
             // here is the problem for the condition 
         }

    }
    return false; 
}
smac89
  • 39,374
  • 15
  • 132
  • 179
cs major
  • 11
  • 1
  • 5
  • 1
    Using `==` is [generally *wrong* for Strings](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839); also, `data[i]"Digit"` is a blatant syntax error - it is parsed equivalently to `data[i] "Digit"` which should make the lack of operator more clear. – user2864740 Jan 31 '16 at 02:29
  • This condition is wrong if (str.isEmpty() == false). Do you want to check that str is not empty? if thats the case you need if(!str.isEmpty()) – Faraz Jan 31 '16 at 02:30
  • @FarazDurrani, that doesn't make it "wrong". They achieve the same thing and, although considered redundant, `boolean == bolean` is valid and checking its results which is also a `boolean` is fine too. – ChiefTwoPencils Jan 31 '16 at 02:49
  • @ChiefTwoPencils Oh thanks. Learned something new. Thank you. – Faraz Jan 31 '16 at 02:50
  • i'm trying to pass my string here and compare it to the pattern for floating number " -/+ 0.00" so that's why i'm taking the data[i] == to then dot or the rest of the sorting method – cs major Jan 31 '16 at 03:40
  • No matter how you look at it, you can't expect the same string to be equal to `"Digit"` ***and*** `"."` ***and*** ... Plus, as another said, you shouldn't be comparing strings with `==`. – ChiefTwoPencils Jan 31 '16 at 04:26
  • 2
    Is there a reason why you don't use Double.parseDouble() and catch the NumberFormatException? – Lars Jan 31 '16 at 04:27
  • @Lars because of conditions of homework, i guess – Ken Bekov Jan 31 '16 at 04:31

4 Answers4

1

The easiest way to test if a String can represent a float is to try to parse it:

String testString = "1.2345";
double result;
try {
  result = Double.parseDouble(testString);
  System.out.println("Success!")
  }
catch (NumberFormatException nfe) {
  // wasn't a double, deal with the failure in whatever way you like
}
Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
  • Yes, I thought of replying that, but the fact that it can be parseable, doesn't mean that it is that. He looks like he is doing something else. Oh well, let's see – João Antunes Jan 31 '16 at 04:35
  • 1
    Not sure what it would mean for a string to be a floating-point number in Java but not pass this test, or for it to pass this test and not be a floating-point number. – Jon Kiparsky Jan 31 '16 at 04:38
  • 1
    The other approach that would make sense, I guess, would be to use a regex. Not a tremendously difficult regex to write, but I can't be bothered to try to get all the details right at the moment. This business of making a little state machine and sliding down an array with it just seems like a lot of trouble for no gain. – Jon Kiparsky Jan 31 '16 at 04:41
  • 1
    @JonKiparsky, but you'll know how to make little state machine. That's the gain. I think, this is educational task. Some kind of homework. – Ken Bekov Jan 31 '16 at 04:45
  • @KenBekov I can respect that. – Jon Kiparsky Jan 31 '16 at 04:45
  • While this works catching `Exceptions` 1.000.000 times is not the fastest. – Adam Arold Mar 08 '18 at 10:05
1

If I understood correctly, the Data array has stuff like ["Digit","Digit",".","Digit"]

So you want the

private static boolean floating(String [] data) { method to return true if the array only has "Digit" entries and exactly one "." entry? is that it?

If so:

boolean foundLeDigit = false;
for (int i = 0; i < data.length; i++) {

     if (data[i].equals("Digit") == false && data[i].equals(".") == false  {
        //we found something other than a Digit or . it's not a float
       return false;
     }
    if(data[i].equals(".")) { 
     if(foundLeDigit) { return false; //as we found 2 "." }
    foundLeDigit = true
    }


}
return foundLeDigit; 
João Antunes
  • 811
  • 9
  • 16
  • It will be valid float, even there is no `.` at all. Standard `Float.parseFloat()` accepts string without `.`. Your last statement should be `return true`. – Ken Bekov Jan 31 '16 at 04:39
  • thanks dude your work is kinda similar to what i want ! but i found something like regular expression ! and we can use it to check if the string is not working or does ! – cs major Jan 31 '16 at 20:15
  • @KenBekov: Indeed Ken, but that does not seem to be what CsMajor wanted. He just wanted to know if there was a decimal part on the number, because the parseFloat can only say if a number can be a float or not i.e. if it's in the range acceptable. And even the number 1 should be. – João Antunes Feb 01 '16 at 15:03
  • CsMajor: you're welcome, but being quite honest: if I knew this was homework, I would have not helped as much, you should struggle, just relax, don't be anxious, and approach this in a rational way, no matter if it takes you 3 hours or 4 to solve something that seems so simple, just do that, and trust me, you'll build the neural pathways to make it easier next time. Oh, and use pen and paper to write things down, if you rely on memory only, it gets tougher and more time consuming, so just draw out. – João Antunes Feb 01 '16 at 15:08
1

The questions lacks a bit of context, so for my answer I'm going to presume that this is homework requiring a manual solution, and that all floating point numbers are supposed to be accepted.

Your approach (while over-engineered) is half-right: you are reducing the input string into classes of characters - digit, sign, exponent marker. What is missing is that now you have to make sure that these character classes come in the right order.

Identify the various parts of float numbers (just look at 0, -1.0, 400E30, 42.1E-30) and you'll see that they come in a specific order, even if some are optional, and that each part imposes restrictions on what characters are allowed there. For example, if there is an 'E' in the number, it has to be followed by a number (with optional sign).

So as you step through the characters of the string, think about how you could keep track of where you are in the number, and base your character validation on that (this is the state machine @JonKiparsky was mentioning).

A few small things:

  • Don't compare strings with '==' - use equalsTo().
  • Think about what it means if sorting() finds a character which is neither a digit, a sign, or the exponent 'E'?
  • You allocate the temps array for 200 entries, but the input string could be larger.
Lars
  • 1,377
  • 6
  • 6
1

using the regular expression is the best way to Handel this problem

private static boolean floating(String [] data) {
        int count =0;
        boolean correct = false;
        for (int i = 0; i < data.length; i++) {

            if (str.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
                System.out.println(" it's a floating number ");
                correct= true;
                break;
             }else 
                 correct = false;

        }if (correct ==true){
            return true;
        }else 
        return false; 

    }
cs major
  • 11
  • 1
  • 5