I have a method which I have to write called personalize. This is what it's suppose to do / what I've done so far.
// personalize takes a String and validates it
// if it is a valid plate, it changes the plateNumber to
// the new plateNumber and calculates the cost of the plate.
// the method returns true if the new plateNumber is valid and the plate was changed,
// and false if the new plateNumber was invalid and no changes were made.
// A personalized plate may be 3 up to 7 chars and 1 space or dash
// Use letters, numbers, dashes, and spaces ONLY
// A personalized plate costs $10 extra plus $5 per letter (not including dashes or spaces)
public boolean personalize(String vanity)
{
boolean valid = true;
vanity = "";
for(int i = 0; i < vanity.length(); i++)
{
if(vanity.length() < 7 && vanity.length() > 3)
{
valid = true;
}
if(Character.isLowerCase(vanity.charAt(i)) || vanity.length() > 7 || vanity.length() < 3 ||
vanity.charAt(i) == '!' || vanity.charAt(i) == '.' || vanity.charAt(i) == '$' ||
vanity.charAt(i) == '#' || vanity.charAt(i) == '*' || vanity.charAt(i) == '_' ||
vanity.charAt(i) == '#' || vanity.charAt(i) == '^' || vanity.charAt(i) == '&')
{
valid = false;
}
}
if(valid = true)
{
plateCost += 25;
}
return valid;
}
I know everything I have in this method isn't completely correct but I'm extremely confused on it. I was thinking about writing a helper method, but I'm unsure if it would be for the cost (newCost) or for the new plate number (personalizedPlate). Or would I have to write both? I'm not simply looking for the answer to my work. I'm really looking for someone to help me through the problem to better understand what to do and why I have to do it that way.
Don't try to do everything in one method. The following code demonstrates one way of implementing these requirements:
public class Plate {
int plateCost = 0;
public boolean personalize(String vanity) {
boolean valid = validate3to7chars(vanity);
valid = valid && hasOnlyOneSpaceOrDash(vanity);
valid = valid && hasValidCharacters(vanity);
if (valid) {
String plateWithoutSpacesAndDashes = vanity.replaceAll(" ", "").replaceAll("-", "");
plateCost = 10 + plateWithoutSpacesAndDashes.length() * 5;
}
return valid;
}
private boolean hasValidCharacters(String vanity) {
String toVerify = vanity.replaceAll(" ", "").replaceAll("-", ""); //remove dashes and spaces
return toVerify.matches("[0-9a-zA-Z]+"); // verify that the place has only numbers and letters
}
private boolean hasOnlyOneSpaceOrDash(String vanity) {
boolean spaces = vanity.lastIndexOf(" ") == vanity.indexOf(" ");
boolean dashes = vanity.lastIndexOf("-") == vanity.indexOf("-");
return spaces && dashes;
}
private boolean validate3to7chars(String vanity) {
return vanity.length() >= 3 && vanity.length() <= 7;
}
public static void main(String[] args) {
Plate p = new Plate();
System.out.println(p.personalize("abc-52s")); // true
System.out.println(p.personalize("123 52s")); // true
System.out.println(p.personalize(" abc62s")); // true
System.out.println(p.personalize("abc56s ")); // true
System.out.println(p.personalize("abc562+")); // false
System.out.println(p.personalize("12345678")); // false
}
}
Related
This question already has answers here:
Get string character by index
(13 answers)
Closed 8 months ago.
Websites commonly require a password that satisfies several requirements. Write a program that checks if an input string satisfies the following (error message is shown for each):
At least 8 characters (Too short)
At least one letter (Missing letter)
At least one number (Missing number)
At least one of these special characters: !, #, % (Missing special)
Output OK, or all related error messages (in above order). If the input string is "Hello", the output is:
Too short
Missing number
Missing special
Hints:
Declare a boolean variable for each requirement.
Use a for loop to visit each character, setting the corresponding boolean to true if satisfied (length is done differently though).
Use the functions Character.isLetter() and Character.isDigit() to detect if a character is a letter or a number.
This is what I have so far for my Java program, but I keep getting errors. Thanks for the help.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String newString;
boolean atLeastEightCharacter;
boolean atLeastOneLetter;
boolean atLeastOneNumber;
boolean atLeastOneSpecialCharacter;
newString = scnr.nextLine();
atLeastEightCharacter = false;
atLeastOneLetter = false;
atLeastOneNumber = false;
atLeastOneSpecialCharacter = false;
if (newString.length() >= 8) {
atLeastEightCharacter = true;
for (int i = 0; i <newString.length(); i++) {
if (Character.isLetter(i)) {
atLeastOneLetter = true;
}
if (Character.isDigit(i)) {
atLeastOneDigit = true;
}
if (newString(i) == '!' || newString(i) == '#' || newString(i)
== '%') {
atLeastOneSpecialCharacter = true;
}
}
}
if (atLeastEightCharacter == false) {
System.out.println("Too short");
}
if (atLeastOneLetter == false) {
System.out.println("Missing letter");
}
if (atLeastOneDigit == false) {
System.out.println("Missing number");
}
if (atLeastOneSpecialCharacter) {
System.out.println("Missing special");
}
}
}
the problem is that you're not checking string's symbols, but indexes, variable i is not char, but integer index
here is fixed version:
for (int i = 0; i <newString.length(); i++) {
char c = newString.charAt(i);
if (Character.isLetter(c)) atLeastOneLetter = true;
if (Character.isDigit(c)) atLeastOneDigit = true;
if (c == '!' || c == '#' || c == '%') atLeastOneSpecialCharacter = true;
}
I need to use a six letter word and if it has a sequence of letter number letter number letter number, then it will be a valid piece of data. Otherwise, it will be considered invalid. The problem with my code is, it always runs it as valid. Here is my code:
vstatus=false;
char a=pcode.charAt(0);
char b=pcode.charAt(1);
char c=pcode.charAt(2);
char d=pcode.charAt(3);
char e=pcode.charAt(4);
char f=pcode.charAt(5);
if(!Character.isLetter(a)) vstatus=true;
if(!Character.isDigit(b)) vstatus=true;
if(!Character.isLetter(c)) vstatus=true;
if(!Character.isDigit(d)) vstatus=true;
if(!Character.isLetter(e)) vstatus=true;
if(!Character.isDigit(f)) vstatus=true;
if (vstatus=true)
{
System.out.println(convertUpperCase(pcode)+" is a valid postal code");
}
if (vstatus=false)
{
System.out.println(convertUpperCase(pcode)+" is not a valid postal code");
}
I gues this would be shorter code for your problem:
String pcode = "aza2a3";
String regex = "[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}";
boolean matches = pcode.matches(regex);
System.out.println(matches);
matches is true if your string is in form that you need and false if i does not match your required string
In your code, even if one character is correct and all the others are wrong, you make it true. You need to confirm that all the characters are correct. Use &&.
String pcode = "i8i8i8";
char a=pcode.charAt(0);
char b=pcode.charAt(1);
char c=pcode.charAt(2);
char d=pcode.charAt(3);
char e=pcode.charAt(4);
char f=pcode.charAt(5);
if (Character.isLetter(a) && Character.isDigit(b) && Character.isLetter(c) && Character.isDigit(d) && Character.isLetter(e) && Character.isDigit(f)) {
System.out.println("valid");
} else {
System.out.println("not a valid postal code");
}
Or, in a loop:
String pcode = "i8i8i8";
boolean flag = true;
for (int i = 0; i < pcode.length(); i++) {
if (!(i % 2 == 0 && Character.isLetter(pcode.charAt(i)) || Character
.isDigit(pcode.charAt(i)))) {
flag = false;
}
}
if (flag) { System.out.println("valid"); }
else { System.out.println("not valid"); }
Ideally, extract the code into a method:
static boolean isPcodeValid(String s) {
for (int i = 0; i < s.length(); i++) {
if (!(i % 2 == 0 && Character.isLetter(s.charAt(i)) || Character
.isDigit(s.charAt(i)))) {
return false;
}
}
return true;
}
Or, use some Java8+ features:
static boolean isPcodeValid(String s) {
return IntStream.range(0, s.length())
.allMatch(i -> i % 2 == 0 && Character.isLetter(s.charAt(i)) || Character
.isDigit(s.charAt(i)));
}
Finally,
You may use this regex:
String r = [A-Za-z][\d][A-Za-z][\d][A-Za-z][\d]
if (pcode.matches(r)) {
// valid
} else {
// invalid
}
5 different ways, choose the one that suits you the best.
I'm in an entry java class, and for one of my programs I am expected to create a ubbi dubbi translator, which ads a ub before every vowel and vowel cluster. I cannot figure out how to get my program to run correctly, and also am unsure how to make it exclude the extra vowel included with the cluster. I am not allowed to use Stringbuilder..
public void buttonPressed()
{
String lowerCase = "";
String userInput = input.getText();
Scanner words = new Scanner( userInput );
String ubbiDubbi = "";
//Splits up user input by line
while (words.hasNext()) {
//Converting to lower case.
lowerCase = words.next().toLowerCase();
System.out.println(lowerCase);
}
for (int i = 0; i < lowerCase.length(); i++) {
if (lowerCase.charAt(i+1) == 'a'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'e') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'i'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'o'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'u') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else {
ubbiDubbi += lowerCase.charAt(i);
}
To get this translator to work you basically just need to step through each character in the input and write it to the output. In addition if the input is a vowel you need to write "ub" out first, except where the previous character was also a vowel.
One thing which is going to be handy is to be able to identify vowels. Starting by writing a function for this is a good idea. It could look like:
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
Now that's in place if you look at the translation, we want to step over every character in the input and write it to the output. This could look like this:
private String translate(String raw) {
String translated = "";
for(char c:raw.toCharArray()) {
// some extra stuff needed here
translated += c;
}
return translated;
}
For the extra stuff you need to know if the current character is a vowel and whether the previous character was a vowel so we can add a little to do this:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false; //
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
And finally to ad "ub" where required you can check if the character is a vowel and whether the last character was a vowel:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
With that in place you just need to hook up the button press action etc. So it might look a little like this:
public class UbbiDubbi {
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
public void buttonPressed() {
String userInput = "";// = input.getText();
Scanner words = new Scanner( userInput );
while (words.hasNext()) {
String lowerCase = words.next().toLowerCase();
String translated = translate(lowerCase);
System.out.println(translated);
}
words.close();
}
public static void main(String...none) {
System.out.println(new UbbiDubbi().translate("The quick brown fox jumps over the lazy aadvark"));
}
}
adding the main method gives an easy way to test out the translation. Hope this helps.
The rest of the code is working perfectly but I cannot figure out how to prevent punctuation from being translated.
public class PigLatintranslator
{
public static String translateWord (String word)
{
String lowerCaseWord = word.toLowerCase ();
int pos = -1;
char ch;
for (int i = 0 ; i < lowerCaseWord.length () ; i++)
{
ch = lowerCaseWord.charAt (i);
if (isVowel (ch))
{
pos = i;
break;
}
}
if (pos == 0 && lowerCaseWord.length () != 1) //translates if word starts with vowel
{
return lowerCaseWord + "way"; // Adding "way" to the end of string
}
else if (lowerCaseWord.length () == 1) //Ignores words that are only 1 character
{
return lowerCaseWord;
}
else if (lowerCaseWord.charAt(0) == 'q' && lowerCaseWord.charAt(1) == 'u')//words that start with qu
{
String a = lowerCaseWord.substring (2);
return a + "qu" + "ay";
}
else
{
String a = lowerCaseWord.substring (1);
String b = lowerCaseWord.substring (0,1);
return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
}
}
public static boolean isVowel (char ch) checks for vowel
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
{
return true;
}
return false;
}
}
I need the translation to ignore punctuation. For example "Question?" should be translated to "estionquay?" (question mark still in the same position and not translated)
As Andreas said, if the function is expecting only one word, it should be the responsibility of the calling function to ensure there's no full sentence or punctuation being passed to it. With that said, if you require the translator to handle this, you need to find the index of the string where the punctuation or non-letter character occurs. I added in a main method to test the function:
public static void main(String[] args) {
System.out.println(translateWord("QUESTION?"));
}
I added a loop into the qu case to find the punctuation being input, the two checks are to see if the character at position i is inside the range of a - z. The sub-string then only goes to the point where the punctuation is found.
int i;
for (i = 0; i < lowerCaseWord.length(); i++) {
if(lowerCaseWord.charAt(i) > 'z' || lowerCaseWord.charAt(i) < 'a') {
break;
}
}
String a = lowerCaseWord.substring (2, i);
String b = lowerCaseWord.substring(i);
return a + "qu" + "ay" + b;
This may need some tweaking if you're worried about words with hyphens and whatnot but this should put across the basic idea.
Here's the output I received:
$javac PigLatintranslator.java
$java -Xmx128M -Xms16M PigLatintranslator
estionquay?
I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated!
public class PhoneNumber {
String phoneNumber;
public PhoneNumber(String num) {
phoneNumber = num;
}
public String decodePhoneNumber() {
// Takes string form phone number and decodes based on number pad
// Find code that makes if statement not care about caps
// so if a || b || c number[cnt] = 1 etc..
for (int cnt = 0; cnt < phoneNumber.length(); cnt++) {
char ch1 = phoneNumber.charAt(cnt);
if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) {
} else if (ch1.equalsIgnoreCase("d" || "e" || "f")) {
} else if (ch1.equalsIgnoreCase("j" || "k" || "l")) {
} else if (ch1.equalsIgnoreCase("m" || "n" || "o")) {
} else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) {
} else if (ch1.equalsIgnoreCase("t" || "u" || "v")) {
} else {
}
}
}
}
You have syntax errors and that is why you cannot find ch1.
Try modifying your code as per this syntax. These changes need to be done in all the conditionals.
if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison:
char ch1 = phoneNumber.toLowerCase().charAt(cnt);
if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') {
// Do something
}
...