i'm trying to tokenize a string in such a way that ...
Example String
Public Static void main(String[args])
String tokenizer tokenize like
public
static
void
main
String
args
but i want to tokenize in such way
public
static
void
main
(
String
[
args
]
)
means its also print the char on which string moves to tokenized
public String[] tokenise(String str){
String progress = "";
LinkedList<String> list = new LinkedList<String>();
for(int c = 0; c < str.length(); c++){
char ch = str.charAt(c);
// Skip next char if the current char is an escape character
if(ch == '\\'){
c++;
continue;
}
// If current char is to be tokenised, add progress and char to list
if(ch == ' ' || ch == '(' || ch == ')' || ch == '[' || ch == ']'){
if(!progress.equals("")) list.add(progress);
list.add(ch+"");
progress = "";
}else{
progress += ch;
}
}
String[] result = new String[list.size()];
for(int c = 0; c < result.length; c++) result[c] = list.get(c);
return result;
}
import java.util.Scanner;
import java.util.ArrayList;
public class SOQ17
{
public Scanner scan;
public String test;
public boolean check = true;
public SOQ17()
{
System.out.print("Enter your string.\n");
scan = new Scanner(System.in);
test = scan.nextLine();
for(int i = 0; i < test.length(); i++)
{
if((test.charAt(i) >= 'A' && test.charAt(i) <= 'Z') || (test.charAt(i) >= 'a' && test.charAt(i) <= 'z'))
{
System.out.print(test.charAt(i) + "");
check = true;
}
else
{
if(check)
{
System.out.println("");
}
System.out.println(test.charAt(i));
check = false;
}
}
}
public static void main(String[] args)
{
while(true)
{
SOQ17 soq = new SOQ17();
}
}
}
Here is how mine works, it will create a new line for every thing that is not a letter. If it is a letter, however, it will simply print it out. Also, I used boolean 'check' to ensure that the proper formatting is applied when alternating back and forth between letter and not.
Related
I need to write an email validation script. It needs to take the email typed in from the user and verify is certain criteria are met and give a true/false. Regex is NOT allowed.
//This is my scanner:
Scanner isValidEmail = new Scanner(System.in);
System.out.print("Please enter your email: ");
String email = isValidEmail.nextLine();
I now need to check using various methods is it has letters, numbers, underscore, only 1 #, etc.
I have written booleans to verify those (examples):
//methos isValidPrefixChar to verify character
public static boolean isValidPrefixChar(char a) {
if (isAlphanumeric(a) || a == '-' || a == '_' || a == '.') {
return true;
} else {
return false;
}
}
//method getDomain() that takes as input a String representing a possible email address.
public static String getDomain(String possibleEmail) {
int i;
for (i = 0; i < possibleEmail.length(); i++) {
if (possibleEmail.charAt(i) == '#') {
break;
}
}
//use a loop to have the character from second half
String domain = "";
int k = i + 1;
while (k < possibleEmail.length()) {
domain = domain + possibleEmail.charAt(k);
k++;
}
return domain;
}
And I have some code that doesn't yet work...
However, I need help in getting the email the user typed in to be the string that gets verified. How do I get the code to check my 'isValidEmail' for these requirements?
EDIT:
Unfortunately, I need to validate each method individually, not as a whole. This doesn't work either because I'm verifying chars in a string.
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner isValidEmail = new Scanner(System.in);
System.out.print("Please enter your email: ");
String email = isValidEmail.nextLine();
public static boolean isAlphanumeric(String email) {
if (email >= 'a' && email <= 'z' || email >= '0' && email <= '9' || s >= 'A' && email <= 'Z') {
return true;
}
return false;
}
}
}
And this for some reason does not work either, which i thought would work!
public static void main(String[] args) {
Scanner isValidEmail = new Scanner(System.in);
String email = isValidEmail.nextLine();
isAlphaNumeric();
}
public static boolean isAlphaNumeric(String email) {
for (int i = 0; i < email.length(); i++) {
char s = email.charAt(i);
if (s >= 'a' && s <= 'z' || s >= '0' && s <= '9' || s >= 'A' && s <= 'Z')
return false;
}
return true;
}
Etc, etc, per method I need to check against?
I had the simple idea to just replace alphanumeric characters by an 'x', and then check if the remaining pattern matches "x#x".
import java.util.Scanner;
class Main {
private static String alphanumericChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your email: ");
String email = scanner.nextLine();
boolean isValidEmail = isEmail(email);
System.out.println(isValidEmail ? "Thank you." : "This is not a valid email.");
}
public static boolean isEmail(String str) {
String pattern = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isAlphanumeric(c)) {
if (pattern.length() == 0 || pattern.charAt(pattern.length() - 1) != 'x') {
pattern += "x"; // add an x as marker for an alphanumeric string.
}
} else {
pattern += c; // add not matching character
}
}
return pattern.equals("x#x"); // check if pattern matches your email-pattern
}
public static boolean isAlphanumeric(char c) {
boolean found = false;
for (int i = 0; i < alphanumericChars.length(); i++) {
if (alphanumericChars.charAt(i) == c) {
found = true;
break;
}
}
return found;
}
}
I'm doing a homework task that is:
Find a unique vowel in the string that is preceded by a consonant, and this consonant is preceded by a vowel.
Example: "eeaaAOEacafu"
Result is: u
What i already did:
Main.class
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stream str = new Stream();
str.setText("eeaaAOEacafu");
System.out.println(str.returnChar(str.getVowel()));
}
Stream.class
public class Stream {
String text;
char vowel;
public String getText() {
return texto;
}
public void setText(String text) {
this.text = text;
}
public char getVowel() {
return vowel;
}
public void setVowel(char vowel) {
this.vowel = vowel;
}
public boolean isVowel(String str) {
str = str.toLowerCase();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(c=='a' || c=='e' || c=='i' || c=='o'|| c=='u') {
return true;
} else {
return false;
}
}
return false;
}
public char returnChar(String str) {
char last;
char next;
char result = '0';
int j=1;
for(int i=0; i<str.length(); i++) {
last = str.charAt(i-1);
next = str.charAt(i+1);
j++;
if(!vogal(str.charAt(i))) {
if(vogal(last) && vogal(next)) {
result = next;
}
}
}
this.setVowel(result);
return result;
} }
This returns: String index out of range: -1
This j=1, was to fix this -1 out of range. It fix but i got new one: out of range 11 because of the next.
The thing is: I have to use pure java and no API.
Can you guys help me?
use regular expressions for the test and locating the character
[aeiouAEIOU][bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]([aeiouAEIOU])
Use a String as a cheap map to keep track of which vowels you've already seen. Also, keep a count of how many consecutive consonants you've encountered. Then, when you hit a vowel that you haven't seen before preceded by a single consonant you've found your answer.
public static void main(String[] args)
{
String s = "eeaaAOEacafu".toLowerCase();
int consCount = 0;
String seenVowels = "";
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if("aeiou".indexOf(c) >= 0)
{
if(seenVowels.indexOf(c) == -1)
{
if(consCount == 1)
{
System.out.println("Result: " + c);
break;
}
seenVowels += c;
}
consCount = 0;
}
else consCount++;
}
}
Output:
Result: u
The above works if we take 'unique' to mean that we haven't seen the vowel before. If the vowel has to be unique within the input string then things are a little more complicated. Now we have to keep track of each vowel that meets the original criteria, but remove the solution if we subsequently encounter another instance of the same vowel.
Here's some code to illustrate:
public static void main(String[] args)
{
String s = "afuxekozue".toLowerCase();
int consCount = 0;
String seenVowels = "";
String answer = "";
for(int i=0; i<s.length(); i++)
{
char c = s.charAt(i);
if("aeiou".indexOf(c) >= 0)
{
if(seenVowels.indexOf(c) == -1)
{
if(consCount == 1)
{
answer += c;
}
seenVowels += c;
}
else if(answer.indexOf(c) >= 0)
{
answer = answer.replaceAll(String.valueOf(c), "");;
}
consCount = 0;
}
else consCount++;
}
if(answer.length() > 0)
System.out.println("Result: " + answer.charAt(0));
}
Output:
Result: o
I am having trouble getting my vowel counter to run in the for loop I created for this cap. Here is my code:
//java app that counts vowels using a forloop
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner ent=new Scanner(System.in);
String string1;
System.out.println("Entered a letter:");
string1 = ent.nextLine();}
public static int numberVowels(String string1){
int count=0;
int vowels=0;
int consonants=0;
for(int i=0; i<string1.length(); i++){
char ch=string1.charAt(i);
if(ch=='a' || ch=='e' ||ch=='i' ||ch=='o'||ch=='u' ){
vowels++;
return ch=ch+vowel;
}else{
consonants++;
}
}
}
}
It says that there is no return type but I do have a return type. What am I doing wrong
You have a return statement in your if (and it looks specious to me), you need one that is guaranteed to be reachable; since your method is for counting vowels you should stick to that. Finally, since you only test lower case vowels, I would recommend calling toLowerCase before your test. Something like,
public static int numberVowels(String string1) {
int vowels = 0;
for (int i = 0; i < string1.length(); i++) {
char ch = Character.toLowerCase(string1.charAt(i));
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
}
return vowels;
}
or using a for-each loop like
public static int numberVowels(String string1) {
int vowels = 0;
for (char ch : string1.toLowerCase().toCharArray()) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
}
return vowels;
}
Yes the message is regarding Java syntax try to fix using this:
always Java check that have returned a variable if your method has a return type.
ยด
//java app that counts vowels using a forloop
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner ent=new Scanner(System.in);
String string1;
System.out.println("Entered a letter:");
string1 = ent.nextLine();}
public static int numberVowels(String string1){
int count=0;
int vowels=0;
int consonants=0;
char tmp='';
for(int i=0; i<string1.length(); i++){
char ch=string1.charAt(i);
if(ch=='a' || ch=='e' ||ch=='i' ||ch=='o'||ch=='u' ){
vowels++;
tmp= ch=ch+vowel;
}else{
consonants++;
}
}
return tmp;
}
`
Declare a string variable for the return value, and initialize it to "".
Use a for loop to iterate over all the characters in the supplied string.
Use a conditional or switch statement to check whether the character is a vowel.
The vowels are 'a','e','i','o', and 'u', uppercase or lowercase.
If it is a vowel, do nothing, otherwise add the character to the return string.
After the loop has completed, return the string.
This is what I have so far, I'm new to this so any help would be appreciated.
public static String removeVowels(String input) {
String s = "";
int f = 0;
for(int i = 0; i < input.length(); i++){
if(c == 'a'|c == 'e'|c == 'i'|c == 'o'|c =='u' | c == 'A' | c == 'E' | c == 'I' | c == 'O' | c == 'U')
f = 1;
else{
s = s + i;
f = 0;
}
}
return s;
}
With the for loop requirement:
private static String removeVowels(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');
vowels.add('A');
vowels.add('e');
vowels.add('E');
vowels.add('i');
vowels.add('I');
vowels.add('o');
vowels.add('O');
vowels.add('u');
vowels.add('U');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!vowels.contains(c)) {
sb.append(c);
}
}
return sb.toString();
}
You could potentially pretty this up in a number of ways, but the above should work.
Without the for loop requirement:
public static String removeVowels(String input) {
return input.replaceAll("[aAeEiIoOuU]","");
}
public class RemoveVowels {
public static void main (String [] args) {
String str = "Hello Good Morning";
String s1 = str.replaceAll("[AEIOUaeiou]" , "");
System.out.println(s1);
}
}
I am writing a pig latin code and I am tripped up by how to get my program to identify where the next vowel in the word is if the first letter in the word is a consonant. Then it moves the first part of the word, up to the first vowel, to the end of the word and prints ay along with it. (ex. trees = eestray)
This is the code I have now
// word is bringing in the string entered from the user
public static void translate(String word) {
String wordCap, pigLatin = "";
char vowels;
int lowest = 0, tempOne, tempTwo, tempThree, tempFour, tempFive;
wordCap = word.toUpperCase();
vowels = wordCap.charAt(0);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
word = word + "way";
System.out.println(word);
}
else {
tempOne = wordCap.indexOf('A', 1);
if (lowest > tempOne && tempOne != -1) {
lowest = tempOne;
}
tempTwo = wordCap.indexOf('E', 1);
if (lowest > tempTwo && tempTwo != -1) {
lowest = tempTwo;
}
tempThree = wordCap.indexOf('I', 1);
if (lowest > tempThree && tempThree != -1) {
lowest = tempThree;
}
tempFour = wordCap.indexOf('O', 1);
if (lowest > tempFour && tempFour != -1) {
lowest = tempFour;
}
tempFive = wordCap.indexOf('U', 1);
if (lowest > tempFive && tempFive != -1) {
lowest = tempFive;
}
public static char vowel(String word) {
int start= 0, end= 0;
char vowels;
for (int i = 0; i < word.length(); i++) {
vowels = word.charAt(i);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
end = i;
break;
}
}
return (char) end;
}
(in translate method)
for (int i = 0; i<wordCap.length(); i++) {
if (vowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
}
}
The problem now is that the vowel method is not an applicable method type. It says it must be a char?
Let me try to shorten that method for you ;)
Try something like this:
private static final char[] vowels = {'a', 'e', 'i', 'o', 'u'};
public static String translate(String word) {
int start = 0; // start index of word
int firstVowel = 0;
int end = word.length(); // end index of word
for(int i = 0; i < end; i++) { // loop over length of word
char c = Character.toLowerCase(word.charAt(i)); // char of word at i, lower cased
if(Arrays.asList(vowels).contains(c)) { // convert vowels to a list so we can use List.contains() convenience method.
firstVowel = i;
break; // stop looping
}
}
if(start != firstVowel) { // if start is not equal to firstVowel, we caught a vowel.
String startString = word.substring(firstVowel, end);
String endString = word.substring(start, firstVowel) + "ay";
return startString+endString;
}
return word; //couldn't find a vowel, return original
}
What this snippet does, is iterate over every character in the word, storing the index of the first vowel in the firstVowel variable. Then, we get every character from firstVowel to end; and store it in startString. Then, we get every character from start to firstVowel; add "ay", and store it in endString. Finally, we concatenate these strings together and return them, resulting in the desired output.
We can test this with System.out.println(translate("trees"));
EDIT: Without array, as requested:
public static String translate(String word) {
char a = 'a';
char e = 'e';
char i = 'i';
char o = 'o';
char u = 'u';
int start = 0;
int firstVowel = 0;
int end = word.length();
for(int i = 0; i < end; i++) {
char c = Character.toLowerCase(word.charAt(i));
if(c == a || c == e || c == i || c == o || c == u) {
firstVowel = i;
break;
}
}
if(start != firstVowel) {
String startString = word.subString(firstVowel, end);
String endString = word.subString(start, firstVowel) + "ay";
return startString+endString;
}
return word;
}
As you can see, arrays shorten things up quite a bit!
If you're feeling pedantic about the Arrays.asList().contains() call, we could define our own:
public static boolean containsChar(char[] lookIn, char lookFor) {
boolean doesContainChar = false;
for(char c : lookIn) {
if(doesContainChar = c == lookFor)
break;
}
return doesContainChar;
}
You might want to use a for loop to iterate through the letters of each word until it finds a vowel. Example:
String wordCap = word.toUpperCase();
char vowels;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
break;
}
}
Of course, I only used isVowel() for the sake of keeping the example concise. You'll have to identify it as a vowel the same way you did in your first if statement (or write an isVowel() method yourself).
For modifying the word, you'll also want to declare a variable to hold the index of the vowel. The previous section of code could be added to for this, like so:
String wordCap = word.toUpperCase();
char vowels;
int vowelIndex;
String newWord;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
vowelIndex = i;
break;
}
}
Then you could reference vowelIndex when modifying the word.
if (vowelIndex == 0) {
newWord = word + "way";
} else {
newWord = word.substring(vowelIndex) + word.substring(0, vowelIndex) + "ay";
}
return word;