IndexOutOfBound error with string manipulation - java

this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.
public class Practice
{
public static void main(String[] args)
{
String a = "hello Stranger";
System.out.println(translate(a)); //8
}
private static String translate(String a)
{
String XD = a;
boolean repeat = true;
int first = 1;
int second = 0;
do
{
second = XD.indexOf(" ");
if (second == -1)
{
repeat = false;
XD = vowelFinder(a);
break;
}
else
{
XD = XD + vowelFinder(a.substring(first, second)); //30
}
first = second +1;
}while(repeat == true);
return XD;
}
private static boolean isVowel (char c)
{
if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
{
return true;
}
return false;
}
private static String vowelFinder(String s)
{
String nope = s;
for(int i = 0; i <= s.length(); i++)
{
if(isVowel(s.charAt(i)) == true)
{
nope = nope.substring(i) + "-"+nope.substring(0, i);`
return nope;
}
}
return nope;
}
}

Try this;
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
String yourSentence="";
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
} while(!yourSentence.equals("quit"));
}
}

Related

Java email validation (No regex allowed)

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

What is wrong with this Vowel question? Out of index

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

Using stack to check equal number of letters and digits in password

I have to write a program to check a password whereby the password should
should be at least 8 characters long
contain only letters and digits(special characters)
contain an equal number of letters and digits
The program should check if it is valid and displays an appropriate message.
Also, only the stack class should be used as the data structure.
Here is what I have come up with so far:
public class dsa_1c {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
String pass;
System.out.println("Enter a password");
pass= sc.nextLine();
if(checkPass(pass)){
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean checkPass(String password){
Stack<Character> stack= new Stack<Character>();
int count1=0, count2=0;
if(password.length()<8){
return false;
}
else{
for(int i=0; i<password.length();i++){
char c= password.charAt(i);
if (!Character.isLetterOrDigit(c)){
return false;}
if(Character.isLetterOrDigit(c)){
stack.push(c);
}
char top= stack.peek();
if(Character.isLetter(top)){
count1++;
stack.pop();
}
else if(Character.isDigit(top)){
count2++;
stack.pop();
}
if(count1==count2){
return true;
}
if(!stack.isEmpty()){
return false;
}
}
}
return true;
}
}
The program when run displays "Valid Password" for any password I type in with more than 8 characters and with no special characters.
It's this part which is apparently the issue
if(count1==count2){
return true;}
because when I change it
if(count1!=count2)
return false; }
it returns Invalid Password for any valid ones.
It's return true in the end that causes an issue. Instead of comparing two counts and returning the values, you can just use return count1 == count2;. Below is an example:
public static boolean checkPass(String password) {
Stack<Character> stack = new Stack<Character>();
int count1 = 0, count2 = 0;
if (password.length() < 8) {
return false;
} else {
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else {
stack.push(c);
}
}
while(!stack.isEmpty()){
char c = stack.pop();
if(Character.isLetter(c)){
count1++;
}else{
count2++;
}
}
return count1 == count2;
}
}
Using a stack seems like overkill to me - it's enough to iterate over the characters, count the digits and the letters, and make sure they have the same number:
private static boolean isValidPassword(String password) {
int letterCount = 0;
int digitCount = ;
for (int i = 0; i < password.length(); ++i) {
char c = password.charAt(i);
if (Character.isLetter(c)) {
++letterCount;
} else if (Character.isDigit(c)) {
++digitCount;
} else {
return false;
}
}
return (letterCount + digitCount) >= 8 &&
letterCount == digitCount;
}
Assuming this is an exercise just to manipulate a stack, here is my 2 cents:
public class dsa_1c {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a password");
String pass = sc.nextLine();
if (checkPass(pass)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
private static boolean checkPass(String pass) {
boolean result = false;
if (pass.length() == 8) {
Stack stack = new Stack();
for (char current : pass.toCharArray()) {
if (stack.isEmpty()) {
stack.push(current);
continue;
}
char previousChar = stack.pop();
if (sameType(current, previousChar)) {
stack.push(previousChar);
stack.push(current);
}
}
if (stack.isEmpty()) {
result = true;
}
}
return result;
}
public static boolean sameType(char current, char previousChar) {
boolean result = false;
if (Character.isAlphabetic(current) && Character.isAlphabetic(previousChar)) {
result = true;
}
else if (Character.isDigit(current) && Character.isDigit(previousChar)) {
result = true;
}
return result;
}
static class Stack extends ArrayList {
public static final char NULL_CHARACTER = 0x0;
public void push(Character letter) {
add(letter);
}
public Character pop() {
Character result = NULL_CHARACTER;
if (!isEmpty()) {
result = (Character)remove(size()-1);
}
return result;
}
}
}

Finding a word with the most consecutive vowels in a text file, using Java

I have a problem in Java that must be solved without anything but the most basic code. It cannot include arrays, and I can't really import anything other than what's showing in my code. The question is this:
The file words.txt on the book’s website contains 87,314 words from the English language.
Write a program that reads through this file and finds the word that has the most consecutive vowels.
I'm brand new to programming, so I've got some ideas of what to do but not precisely how to put it all together. I'm really stuck on this question. Any help would be much appreciated.
Here's what I've come up with, but it's clearly incorrect, and I've already spent many hours on it, including researching here and other places, and trying the code I found. I'm not expecting anyone to do the homework for me, but if you could give me some guidance, it would be very much appreciated. Here's what I have so far:
package vowels;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Vowels
{
public static void main(String[] args)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("words.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
System.exit(0);
}
String eachWord = fileIn.next();
String mostConsecutiveVowels = "";
int w = 0;
int z;
int consecutiveVowels = 0;
int mostConsecutiveVowelsInWord = 0;
int wordWithMostConsecutiveVowels = 0;
boolean vowel;
boolean previousVowel;
boolean mostVowels;
while (fileIn.hasNext())
{
while(consecutiveVowels >= mostConsecutiveVowelsInWord)
{
mostVowels = true;
}
char a = eachWord.charAt(w);
if (a=='a'||a=='e'||a=='i'||a=='o'||a=='u')
{
consecutiveVowels++;
consecutiveVowels = mostConsecutiveVowelsInWord;
}
for(z = 1; z <= eachWord.length(); z++)
{
char b = eachWord.charAt(z);
char c = eachWord.charAt(z-1);
while (b=='a'||b=='e'||b=='i'||b=='o'||b=='u')
{
vowel = true;
}
while (c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
{
previousVowel = true;
}
if (vowel = false && previousVowel = true && mostVowels = false;)
{
consecutiveVowels = 0;
}
else if (vowel = false && previousVowel = true && mostVowels = true;)
{
consecutiveVowels = mostConsecutiveVowelsInWord;
}
else if (vowel = true && previousVowel = false)
{
consecutiveVowels = 1;
}
else if (vowel = true && previousVowel = true && mostVowels = true;)
{
consecutiveVowels++;
consecutiveVowels = mostConsecutiveVowelsInWord;
}
else if (vowel = true && previousVowel = true && mostVowels = false;)
{
consecutiveVowels++;
}
}
}
if (mostVowels)
{
if(eachWord.length()>mostConsecutiveVowels.length())
{
mostConsecutiveVowels = eachWord;
}
}
System.out.println("The word in words.txt with the most consecutive vowels is " + mostConsecutiveVowels);
fileIn.close();
}
}
This is my solution. However, you should try coming up with your own as well for practice, and if you want to use the comments in my code as suggestions.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Vowels {
public static final String WORD_FILE = "words.txt";
public static void main(String[] args) {
try (Scanner fileScanner = new Scanner(new FileInputStream(WORD_FILE))) {
String targetWord = null; // word with most consecutive vowels
int maxConsecutiveVowels = 0;
while (fileScanner.hasNext()) {
// for each word in the file
String word = fileScanner.next().toLowerCase();
int consecutiveVowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxConsecutiveVowels + consecutiveVowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxConsecutiveVowels
if (isVowel(word.charAt(i))) {
// consonants reset this to 0
consecutiveVowels++;
} else {
// reached the end of the vowels so check if we beat maxConsecutiveVowels
if (consecutiveVowels > maxConsecutiveVowels) {
maxConsecutiveVowels = consecutiveVowels;
targetWord = word;
}
consecutiveVowels = 0;
}
}
// reached the end of the vowels at the end of the word so check if we beat maxConsecutiveVowels
if (consecutiveVowels > maxConsecutiveVowels) {
maxConsecutiveVowels = consecutiveVowels;
targetWord = word;
}
}
if (targetWord == null) {
System.out.println("there are no words with vowels in " + WORD_FILE);
} else {
System.out.println("the word in " + WORD_FILE + " with the most consecutive vowels is '" + targetWord + "'");
System.out.println("it has " + maxConsecutiveVowels + " consecutive vowels");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static boolean isVowel(char c) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
}
return false;
}
}

NullPointerException using Scanner

I am new to programming and I'm starting to create a simple calculator in Java, but I keep getting an error on the line
for (int i = 0; i < user_input.length(); i++)
The error says:
Exception in thread "main" java.lang.NullPointerException
How can I fix this problem?
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
public class stringCalculator
{
public static ArrayList<String> input = new ArrayList<String>();
public static ArrayList<String> calcOperators = new ArrayList<String>();
public static ArrayList<Integer> calcOperands = new ArrayList<Integer>();
public static String user_input;
public static String first;
public static int int1;
public static String char1;
public static int int2;
public static String next;
}
public static void input()
{
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
}
public void calcOperators()
{
for (int i = 0; i < user_input.length(); i++)
{
if (char1 == "+")
{
calcOperators.add(char1);
}
else if (char1 == "-")
{
calcOperators.add(char1);
}
else if (char1 == "char1")
{
calcOperators.add(char1);
}
else if (char1 == "/")
{
calcOperators.add(char1);
}
}
public void calcOperands()
{
for (int i = 0; i < user_input.length(); i++)
{
if (int1 == 1 || int2 == 1)
{
calcOperands.add(1);
}
else if (int1 == 2 || int2 == 2)
{
calcOperands.add(2);
}
else if (int1 == 3 || int2 == 3)
{
calcOperands.add(3);
}
else if (int1 == 4 || int2 == 4)
{
calcOperands.add(4);
}
else if (int1 == 5 || int2 == 5)
{
calcOperands.add(5);
}
else if (int1 == 6 || int2 == 6)
{
calcOperands.add(6);
}
else if (int1 == 7 || int2 == 7)
{
calcOperands.add(7);
}
else if (int1 == 8 || int2 == 8)
{
calcOperands.add(8);
}
else if (int1 == 9 || int2 == 9)
{
calcOperands.add(9);
}
else if (int1 == 0 || int2 == 0)
{
calcOperands.add(0);
}
}
}
}
public class Main
{
public static void main(String[] args)
{
stringCalculator c = new stringCalculator();
c.input();
c.calcOperators();
c.calcOperands();
}
}
I am kind of confused in here why you have
public static String user_input
and then
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
And finally you are using the same var name for strings and ints in loops:
for (int i = 0; i < user_input.length(); i++)
for (int i = 0; i < user_input.length(); i++)
I would highly recommend refactoring this code.
.....
private ArrayList<String> input = new ArrayList<String>();
private ArrayList<String> calcOperators = new ArrayList<String>();
private ArrayList<Integer> calcOperands = new ArrayList<Integer>();
private String user_input;
private String first;
private String next;
private String char1;
private int integer2;
private int integer1;
}
public static void input()
{
Scanner input = new Scanner(System.in);
int int1 = input.nextInt();
int int2 = input.nextInt();
string str = input.next();
string nxt = input.next();
setInteger1(int1);
setInteger2(int2);
setStringFirst(str);
setStringNext(...);
....
// And so on
}
private void setInteger1(int int1) {
this.integer1 = int1;
}
private Integer getInteger1() {
return this.integer1;
}
private void setInteger2(int int2) {
this.integer2 = int2;
}
private Integer getInteger2() {
return this.integer2;
}
private void setStringFirst(String fst) {
this.first = fst;
}
private String getStringFirst() {
return this.first;
}
// And so on. Create all get and set methods for each global variable and for future
// reference do not use variable names that are the same as method, names
// and try to use more meaningful variable names. In fact, if you look at
// Java naming conventions it would do you good.
Could you also tell us perhaps what these loops are meant to do? As I don't really understand what is this? Do you want to iterate over an array of "things" and match each operation to given array element? Or do you just want a single element to match one of the operations?
Side note: Class names should be capitalized:
public class StringCalculator
==================================================================================
OK, I have made a simple program that allows you to add a string into an array and then display it. It is based on what you were doing although you will see it is structured differently. This should give you a head start and allow you to implement this further and finish whatever you are doing.
public class Thing {
private String operator;
private void getUserInput() {
Scanner input = new Scanner(System.in);
if(input.hasNextInt()) {
System.out.println("I have entered an integer: " + input.nextInt());
}
else {
setOperator(input.nextLine());
addOperators();
System.out.println("I have entered a string: " + getOperator());
}
displayThing();
}
private ArrayList<String> addOperators() {
ArrayList<String> operatorsList = new ArrayList<String>();
if(getOperator().equals("+")) {
operatorsList.add(operator);
}
if(getOperator().equals("-")) {
operatorsList.add(operator);
}
else {
operatorsList.add(getOperator());
}
return operatorsList;
}
private void displayThing() {
System.out.println(addOperators());
}
public static void main(String[] args) {
Thing program = new Thing();
program.getUserInput();
}
// Setters and getters
private void setOperator(String operator) {
this.operator = operator;
}
private String getOperator() {
return this.operator;
}
}
You have declared the public static String user_input; which is used in a for loop and not initialised, so thus the exception. Initialise it in your input method, like this.user_input=user_input.nextLine().
You have a static String named user_input defined as:
public static String user_input; // This is null and what the for loop is reading
Set a value to that string when you're using your Scanner... which you shouldn't have also named user_input.

Categories

Resources