-1

I am new to java and I am trying to work with the stringBuilder at the moment. my current project will allow the user to input a "colors.txt" file. I want to verify that the entered string is valid. The information that is entered is: Had to parenthesize the # but it need to be taken out and reentered on the valid output. (#)F3C- valid, ouput(#FF33CCFF) (#)aa4256- valid, output(AA4256FF) (#)ag0933 - is invalid because 'g' is not hexadecimal (#)60CC- valid, output(6600CCFF) 095- valid, output(009955FF) Be0F- valid, output(BBEE00FF) (#)AABB05C- invalid, to many characters (7)

So the output to another file called "-norm" appended to the name of the file before the dot ".". I want to verify if the entered line is a true hexadecimal color. Also the out put has to have the validated line equal 8 by doubling the characters, if the double does not equal 8 then "FF" has to be appended to it.

I was able to input the file however without verification. It will read each line and go through 2 methods(Just learning as well) for verification. I am having a lot of issues with my code. I can visualize and know what I want to do, I am having an issue translating that into code.

Thank you for all your help!

 import java.util.*;  // for Scanner
import java.io.*;  // for File, etc.
import java.lang.*;
//import java.awt.* //to use the color class

public class RGBAColor
{
      //Scanner file = new Scanner(new File("colors.txt"));

      public static void main(String[] args) //throws IOException
          throws FileNotFoundException
      {  
         Scanner console = new Scanner(System.in);
         System.out.println("Please make sure you enter the colors.txt ");

         //assigning the colors file
         String fileName = console.nextLine();
         Scanner inputFile = new Scanner(new File(fileName));

         //outputing to colors-norm file
         int dotLocation;

         StringBuilder dot = new StringBuilder(fileName);
         dotLocation = dot.indexOf(".");

         //PrintWriter FileName =
         //new PrintWriter("colors-norm.txt");

           while (inputFile.hasNextLine())
               {
                  String currLine = inputFile.nextLine();
                  int lineLenght = currLine.length();
                  //System.out.printf("line length is %s \n", currLine);
                  verification(currLine);          

               }

               inputFile.close();
      }

          //this will verify the color
          public static void verification(String line)
          {
               StringBuilder newString = new StringBuilder(line);

               //will be used to compare the length

               int stringLength;

               //will remove the # if in string
               if (newString.charAt(0) == '#')
               {
                   newString = newString.deleteCharAt(0);

               }

                    //assigns the length 
               stringLength = newString.length();

                  //checks the length of the string
                  //prompt will show if the number of digits is invalid
                  if (!(stringLength == 3 || stringLength == 4 || stringLength == 6 || stringLength == 8))
                  {
                        System.out.println("invalid number # of digits " + stringLength + " in "
                                            + newString);
                  }                      
                  StringBuilder errorLessString = new StringBuilder("");

                   //checks number and letter for valid entries for hexadecimal digit                
                  for (int i = 0; i < newString.length(); i++ )
                  {     
                        char valid = newString.toString().toUpperCase().charAt(i);
                        if (!(valid >= '0' && valid <= '9' || valid >= 'A' && valid <= 'F'))
                        {
                              System.out.println("invalid color '" + newString.charAt(i) + 
                                             "' in " + newString );
                        }

                       errorLessString.append(valid);                        
                  }

              System.out.println("this is the length of  " + errorLessString + "  " + errorLessString.length());

                   String resultingString = " ";

           // validating length only allowing the correct lengths of 3,4,6,and 8      
               switch (errorLessString.length())
               {
                  case 3:  System.out.println("begin case 3");
                            dbleAppend(newString.toString());
                            addFF(newString.toString());
                            System.out.println("end case 3");
                        break;

                  case 4:   dbleAppend(newString.toString());                           
                        break;


                  case 6:  addFF(newString.toString());
                        break;

                  case 8:

               }
          }

          //method to have two characters together
          public static String dbleAppend(String appd)
          {
                  StringBuilder charDouble = new StringBuilder("");

                  //pass in append string to double the characters
                  for (int i = 0; i < appd.length(); i++)
                  {
                        charDouble.append(appd.charAt(i));
                        charDouble.append(appd.charAt(i));
                  }
                  return appd;
          }

         //method will append ff to string
         public static String addFF(String putFF)
         {
               StringBuilder plusFF = new StringBuilder("FF");                            

                     plusFF.append(putFF.toString());

               System.out.println(plusFF);

               return putFF;
         }
}
elp
  • 840
  • 3
  • 12
  • 36
  • 1. read this: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ 2. Please reformat your posted code so it's easier to read and list (all) the specific issues you have – larsgrefer Apr 28 '18 at 20:55
  • I went through the edit process that was given in my inbox. I hope that is what you were referring to. listing the issues that I am having 1) someone suggested finding the index of the "." and appending the "-norm" so the output file will be whatever file name the user enters with "-norm" attached but before the ".". 2) I want to validate the text file to make sure they are entering a valid file. Do I have to validate each separate part? or the whole string? 3) also writing to a file is a huge issue, I was able to read in the file. 4) the output file can only hold the valid inputs. Thank you! – Jason Glenn Apr 28 '18 at 22:54
  • Could you add an example for a valid `colors.txt` file? Are multiple colors per file allowed? If so how are they separated? – larsgrefer Apr 28 '18 at 23:03
  • Please write a better title that will help Google index this page based on the real or perceived issue. – Dexygen Apr 28 '18 at 23:33

1 Answers1

0

1) someone suggested finding the index of the "." and appending the "-norm" so the output file will be whatever file name the user enters with "-norm" attached but before the ".".

So you are unsure whats the best way to get from colors.txt to colors-norm.txt or from foo.txt to foo-norm.txt?

One option is to find the index of the (last) dot in the file name and to split the filename at this point and use the parts to construct the new filename:

String filename = "colors.txt"

int indexOfDot = filename.lastIndexOf(".");
String firstPart = filename.substring(0, indexOfDot); // Will be "colors"
String lastPart = filename.substring(indexOfDot); // Will be ".txt"
return firstPart + "-norm" + lastPart;

A more elegant option is to use a regular expression:

String filename = "colors.txt"

Matcher filenameMatcher = Pattern.compile("(.*)\\.txt").matcher(filename);
if (matcher.matches()) {
    String firstPart = matcher.group(1) // Will be "colors"
    return firstPart + "-norm.txt"
} else {
    //Invalid input, throw an Exeption and/or show an error message
}

If other file extensions than .txt are allowed you'd have to capture the extension too.

2) I want to validate the text file to make sure they are entering a valid file. Do I have to validate each separate part? or the whole string?

The easiest way is to first separate the different color values an then validate each color value. You might want to develop a grammar first, so writing the actual code will be easier.

Since there is only one value per line you could use something like this:

List<String> outputColors = Files.lines(new File(fileName).toPath())
    .filter(line -> isValidColor(line))
    .map(validColor -> convertToOutputFormat(validColor))
    .collect(Collectors.toList());

Files.write(new File(outputFileName).toPath(), outputColors);

3) also writing to a file is a huge issue, I was able to read in the file.

Google is you friend:

4) the output file can only hold the valid inputs.

After you solved 2) properly, this shouldn't be a big problem

larsgrefer
  • 2,735
  • 19
  • 36
  • Could you add an example for a valid colors.txt file? Are multiple colors per file allowed? If so how are they separated? – larsgrefer the file will contain any amount of colors valid and invalid. I looked up these hexadecimal values- #F3C- valid, ouput will be #FF33CCFF. #aa4256- valid, output #AA4256FF. #ag0933 - is invalid because 'g' is not hexadecimal. #60CC- valid, output #6600CCFF. 095- valid, output #009955FF. Be0F- valid, output #BBEE00FF. #AABB05C- invalid, to many characters (7). – Jason Glenn Apr 28 '18 at 23:52
  • Is there one value per line? are the values separated by a comma, semicolon or whitespace? – larsgrefer Apr 28 '18 at 23:54
  • Yes each value is on a separate line, the program will read in each line and validate each line. – Jason Glenn Apr 29 '18 at 00:01