stringBuilder killed my brain - java

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;
}
}

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:
http://www.baeldung.com/java-write-to-file
How do I create a file and write to it in Java?
https://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
4) the output file can only hold the valid inputs.
After you solved 2) properly, this shouldn't be a big problem

Related

How to resolve the following program with a for loop into producing an appropriate output?

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}

How can I replace certain characters within a String in Java?

I have a program that reads an input (a String) and prints that String reversed. Now, I need to read through the reversed String and replace all of the "A"s with "T"s, the "T"s with "A"s, the "G"s with "C"s and the "C"s to "G"s. So basically, the "complement". I tried to use multiple lines with a replace function but once the "A"s are turned into "T"s, it will replace all of those into "A"s so there are no "T"s at all. How can I replace the characters so that they do not override each other?
Here is my code if it helps! I don't have any functions to get the "complement" yet, but here is what I'm working with.
import java.util.*;
public class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read;
read = new Scanner(System.in);
String input = read.next();
String reverse="";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
}
}
You can convert your reverse string to a char array like this:
char[] charArr = reverse.toCharArray();
Then you can iterate through it and change the characters that you want:
for(int i = 0; i < charArr.length; i++){
if(charArr[i] == 'A'){
charArr[i] = 't';
}
}
At the end you can convert the char array back to a string like this:
String str = new String(charArr);
Here is a code sample that you can try:
import java.util.Scanner;
class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read = new Scanner(System.in);
String input = read.next();
String reverse="";
StringBuilder sb = new StringBuilder();
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
for (char c: input.toCharArray()) { // user 'reverse' to operate on reversed string
switch (c) {
case 'A' : sb.append('T'); break;
case 'T' : sb.append('A'); break;
case 'G' : sb.append('C'); break;
case 'C' : sb.append('G'); break;
default : sb.append(""); break; // handle you're exceptions here
}
}
System.out.println("x: " + sb);
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
read.close();
}}
Well, switch-case is a kind of mapping technique which will map your case (as key) with it's values. In this case:
I am replacing 'A' with 'T' where the string contains 'A' by appending into the StringBuilder (to create a new string) and then break; which is a mandatory statement for single time execution only.
And the default keyword is for default case, which means if all of the cases are unsatisfied to be executed then the default case is called, you can do whatever you want to do by default if no case, condition matched.
Well, for your last question, You can make it generic if the problem states some pattern; if not you, unfortunately have to do it manually.
Use the replace method, but change your values to a "temporary" character. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
Replace T -> x
Replace A -> T
Replace x -> A
Repeat for all your pairs.

How to replace multiple occurences of a character in a java string using replace and charAt methods

This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}

Java: How do I ensure, or make a user, input a comma in a string?

First off, I am brand new to both Java and to this website. I am going to ask my question as thoroughly as I can. However, please let me know if you think I left something out.
I am working on a school assignment, and I am stuck on the second portion of it. I am able to prompt the user, but can not for the life of me, figure out how to ensure that the input string contains a comma. I did try searching this site, as well as Googling it, and haven't been able to find anything. Perhaps I am not wording the question appropriately.
(1) Prompt the user for a string that contains two strings separated by a comma.
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
So far I have this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter string seperated by a comma: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
// Create new input string stream
inSS = new Scanner(lineString);
// Now process the line
firstWord = inSS.next();
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
if else (lineString != ",") { // This is where I am stuck!
System.out.print("No comma in string");
}
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
I know my "if else" is probably not correct. I just don't know where to begin for this particular command. Unfortunately my eBook chapter did not cover this specifically. Any thoughts would be greatly appreciated. Thank you so much!
I suspect you want to assert if the input contains a comma, and at least one letter either side. For this you need regex:
if (!input.matches("[a-zA-Z]+,[a-zA-Z]+")) {
System.out.print("Input not two comma separated words");
}
Since you are looking for a string with a comma in it and you want to get the string “Before” the comma and the string “After” the comma, then string.split(‘,’) is what you want. Asking if the string “Contains” a comma gives you no information about the string before or after the comma. That’s where string.split() helps. Since you don’t care “Where” the comma is you simply want the string before the comma and the string after the comma. The string.split(‘,’) method will return a string array containing the strings that are separated by commas (in your case) or any character.
Example:
string myString = “firstpart,secondpart”;
… then
string[] splitStringArray = myString.Split(‘,’)
This will return a string array of size 2 where
splitStringArray[0] = “firstpart”
splitStringArray[1] = “secondpart"
with this info you can also tell if the user entered the proper input… i.e…
if the splitStringArray.Length (or Size) = 0, then the user did not input anything, if the splitStringArray.Length (or Size) = 1 then the user input 1 string with no commas… might check for exit here. If the splitStringArray.Length (or Size) = 2 then the user input the string properly. if the splitStringArray.Length (Size) > 2 then the user input a string with more than 1 comma.
I hope that helps in describing how string.split works.
Your code however needs some work… without going into much detail below is a c# console while loop as an example:
inputDone = false;
while (!inputDone)
{
Console.Clear();
Console.WriteLine("Enter string seperated by a comma: ");
lineString = Console.ReadLine();
string[] splitStringArray = lineString.Split(',');
// check for user to quit
if (splitStringArray.Length == 1)
{
if (splitStringArray[0] == "q")
{
inputDone = true;
Console.Clear();
}
else
{
// 1 string that is not "q" with no commas
}
}
if (splitStringArray.Length == 2)
{
// then there are exactly two strings with a comma seperating them
// or you may have ",string" or "string,"
Console.WriteLine("First word: " + splitStringArray[0]);
Console.WriteLine("Second word: " + splitStringArray[1]);
Console.ReadKey();
}
else
{
Console.WriteLine("Input string empty or input string has more than two strings seperated by commas");
Console.ReadKey();
}
}
Hope that helps.
This worked for me:
import java.util.Scanner;
import java.io.IOException;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String nextWord = "";
System.out.println("Enter input string: ");
while (lineString.matches("q") == false) {
lineString = scnr.nextLine();
lineString = lineString.replaceAll(",",", ");
inSS = new Scanner(lineString);
int delimComma = lineString.indexOf(",");
if ((delimComma <= -1) && (lineString.matches("q") == false)) {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
else if ((delimComma <= -1) && (lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2) && (lineString.matches("q") == false)) {
System.out.println("Error: Two words");
System.out.println("Enter input string: ");
}
else if (lineString.matches("q") == false) {
firstWord = inSS.next();
nextWord = inSS.nextLine();
System.out.println("First word: " + firstWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("Second word: " + nextWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("\n");
System.out.println("Enter input string: ");
}
continue;
}
return;
}
}

For loop iterating through string and adding/replacing characters

I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.

Categories

Resources