In my program I need to insert - between two odd numbers and * between even numbers and ignore if there is 0. For example:
Input = 99946 Output = 9-9-94*6
Input = 56647304 Output = 56*6*47-304
Method getDigits() places the digits of the entered number into array cells. Method insertDashesAsteriks() returns properly concatenated String.
But when I run my program with the following example:
Please enter the numbers so they could be rearranged:
222234411110000
Exception in thread "main" java.util.InputMismatchException: For input string: "222234411110000"
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at DashInsert2.main(DashInsert2.java:9)
then I'm getting InputMismatchException. Why am I getting the error?
import java.util.Scanner;
public class DashInsert2 {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Please enter the numbers so they could be rearranged: ");
int nums = kbd.nextInt();
int[] numArray = getDigits(nums);
System.out.println("The array representation of the numbers is \n");
System.out.println();
String result = insertDashesAsteriks(numArray);
System.out.println("The result is " + result);
}
public static int[] getDigits(int numbers)
{
int length = Integer.toString(numbers).length();
int[] temp = new int[length];
for(int i = 0; i < length; i++)
{
temp[i] = numbers % 10;
numbers = numbers / 10;
}
return temp;
}
public static String insertDashesAsteriks(int[] numArray)
{
String temp = "";
for(int i = 1; i < numArray.length; i++)
{
if(numArray[i] % 2 == 0 && numArray[i-1] % 2 ==0)
{
temp = numArray[i-1] + "*" + numArray[i] + "*";
}
else if(numArray[i] == 0 || numArray[i-1] == 0)
{
temp = numArray[i-1] + "" + numArray[i] + "";
}
else if(numArray[i] % 2 != 0 && numArray[i-1] % 2 != 0)
{
temp = numArray[i-1] + "-" + numArray[i] + "-";
}
}
return temp;
}
}
Maximum value for int is 2,147,483,647
You entered: 222,234,411,110,000
You'll need to treat the number as a string since the number you input is past the biggest possible 32 bit integer.
Try kbd.next().charAt(0); to parse it character by character instead.
First off, if you're reading in ints, you're limited to their range. That means numbers beyond about +/- two billion are out of the question. For handling larger number, you can move to larger data types (like long) or just handle strings, which have far less stringent limitations.
Once you are handling strings, there's a far simpler way (in terms of the code you have to write) to do this substitution using regular expressions:
public class Test {
static String morph(String s) {
String oldS;
do {
oldS = s;
s = s.replaceAll("([13579])([13579])", "$1-$2");
s = s.replaceAll("([2468])([2468])", "$1*$2");
} while (! s.equals(oldS));
return s;
}
public static void main(String args[]){
System.out.println(morph("99946"));
System.out.println(morph("56647304"));
System.out.println(morph("222234411110000"));
}
}
The morph function simply modifies the string with your substitution rules until it ceases to change. The output of the test harness (using the data you supplied) is:
9-9-94*6
56*6*47-304
2*2*2*234*41-1-1-10000
Now it may be that, if this is a classwork assignment, you're limited in the language facilities you can use. But, since you haven't mentioned that, and no coder in their right mind would (usually) choose a more difficult path, you should consider the use of the regular expression method. Code that is shorter is almost always less prone to bugs.
If you don't want to use regular expressions, you can still make your code relatively short and well structured, with something like:
// Helper functions for inserting characters.
static boolean is2468 (char ch) {
return (ch == '2' || ch == '4' || ch == '6' || ch == '8');
}
static boolean is13579 (char ch) {
return (ch == '1' || ch == '3' || ch == '5' || ch == '7' || ch == '9');
}
static String morph(String str) {
// Use efficient string builder for creating morphed string.
StringBuilder newStr = new StringBuilder();
// Last/current character, starting with '0' simplifies
// start condition.
char lastCh, ch = '0';
// Process every character in string.
for (int idx = 0; idx < str.length(); idx++) {
// Transfer previous current to last, get current.
lastCh = ch;
ch = str.charAt(idx);
// Put '-' between two odds, '*' between two non-zero evens.
if (is13579(lastCh) && is13579(ch))
newStr.append('-');
else if (is2468(lastCh) && is2468(ch))
newStr.append('*');
// Put character there regardless.
newStr.append(ch);
}
// Return string version of string builder.
return newStr.toString();
}
Related
I am learning Java and wonder how I can get two numbers in same line.
Is this algorithm is okay, what can I do improve? What can you suggest me?
import java.util.Scanner;
public class Main{
public static int Separate(String Values, int Order){
String toReturn = "";
int Counter = 0;
for(int Iterator = 0; Iterator < Values.length(); Iterator = Iterator + 1){
if(Values.charAt(Iterator) == ' ') {
if(Order == Counter) break;
else{
toReturn = "";
Counter = Counter + 1;
}
}
else toReturn += Values.charAt(Iterator);
}
return Integer.parseInt(toReturn);
}
public static void main(String[] args){
Scanner Entry = new Scanner(System.in);
System.out.print("Enter two numbers separated by space: ");
String Number = Entry.nextLine();
int Frst = Separate(Number, 0);
int Scnd = Separate(Number, 1);
}
}
what can I do improve? What can you suggest me?
Adopt the Java Naming Conventions:
Method Names are camelCase, starting with a lower case letter
Field and Property Names and Method Argument Names are camelCase, too
Basically only Class and Interface Names start with an upper case letter in Java.
public static int separate(String values, int order){
String toReturn = "";
int counter = 0;
for(int iterator = 0; ...) { ...
Else I'd say: This algorithm is pretty solid for a beginner. It's easy to understand what's going on.
Of course Java provides much more sophisticated tools to solve this, using for example Regular Expressions with myString.split(...), or Streams with IntStream intStream = myString.chars().
Last but not least you could add Exception Handling: What happens if Integer.parseInt is given some non-number? It will crash.
try {
return Integer.parseInt(toReturn);
} catch (NumberFormatException e) {
// when "toReturn" cannot be parsed to an int, return a
// default value instead of crashing your application
return 0;
}
Or if crashing is the desired behavior, or you can ensure that this method is never called with an illegal String, leave it as it is (= don't add try catch)
I think what you've done is great for well-formatted input, where you have a single space character between the numbers. As others have pointer out, following Java naming conventions will greatly improve the readability of your code.
Handling sequences of space characters, possible before, between, and after your numbers is a little tricky. The general pattern would be to consume any sequences of spaces, remember the current position, consume the sequence of digits, then if we're at the correct position return the parsed number.
public static int separate(String str, int order)
{
for(int i = 0, pos = 0; ; pos++)
{
while(i < str.length() && str.charAt(i) == ' ') i += 1;
int j = i;
while(i < str.length() && str.charAt(i) != ' ') i += 1;
if(i == j) throw new IllegalStateException("Missing number!");
if(order == pos)
{
// handle NumberFormatException
return Integer.parseInt(str.substring(j, i));
}
}
}
Test:
String s = " 23432 798 44";
for(int i=0; i<3; i++)
System.out.print(separate(s, i) + " ");
Output:
23432 798 44
Given a random character string not including (0-9), I need to shorten the representation of that string by adding the number of consecutive characters. For e.g: ggee will result in g2e2 being displayed.
I managed to implement the program and tested it (works correctly) through various inputs. I have run into the issue where I cannot seem to understand how the character "e" is displayed given the input above.
I have traced my code multiple times but I don't see when/how "e" is displayed when "i" is 2/3.
String input = new String("ggee");
char position = input.charAt(0);
int accumulator = 1;
for (int i = 1; i < input.length(); i++)
{
// Correction. Was boolean lastIndexString = input.charAt(i) == (input.charAt(input.length() - 1));
boolean lastIndexString = i == (input.length() - 1);
if (position == input.charAt(i))
{
accumulator++;
if (lastIndexOfString)
System.out.print(accumulator); // In my mind, I should be printing
// (input.charAt(i) + "" + accumulator); here
}
else //(position != input.charAt(i))
{
if (accumulator > 1)
{
System.out.print(position + "" + accumulator);
}
else
{
System.out.print(position + "");
}
position = input.charAt(i);
accumulator = 1;
if (lastIndexOfString)
System.out.print(input.charAt(i)); // This is always printing when
// I am at the last index of my string,
// even ignoring my condition of
// (position == input.charAt(i))
}
}
In Java 9+, using regular expression to find consecutive characters, the following will do it:
static String shorten(String input) {
return Pattern.compile("(.)\\1+").matcher(input)
.replaceAll(r -> r.group(1) + r.group().length());
}
Test
System.out.println(shorten("ggggeecaaaaaaaaaaaa"));
System.out.println(shorten("ggggee😀😀😀😁😁😁😁"));
Output
g4e2ca12
g4e2😀6😁8
However, as you can see, that code doesn't work if input string contains Unicode characters from the supplemental planes, such as Emoji characters.
Small modification will fix that:
static String shorten(String input) {
return Pattern.compile("(.)\\1+").matcher(input)
.replaceAll(r -> r.group(1) + r.group().codePointCount(0, r.group().length()));
}
Or:
static String shorten(String input) {
return Pattern.compile("(.)\\1+").matcher(input)
.replaceAll(r -> r.group(1) + input.codePointCount(r.start(), r.end()));
}
Output
g4e2ca12
g4e2😀3😁4
Basically you want each char with no of repeats.
*******************************************************************************/
public class Main
{
public static void main(String[] args) {
String s="ggggggeee";
StringBuilder s1=new
StringBuilder("") ;
;
for(int i=0;i<s.length();i++)
{
int count=0,j;
for( j=i+1;j<s.length();j++)
{
if(s.charAt(i)==s.charAt(j))
count++;
else
{
break;}
}
i=j-1;
s1=s1.append(s.charAt(i)+""+(count+1));
}
System.out.print(s1);
}}
Output
import java.util.*;
class Dis {
static boolean Digitinstring(String s) {
boolean result = false;
int i, j;
char[] ch = s.toCharArray();
int x = ch.length;
for (j = 0; j < x; j++) {
for (i = 0; i <= 9; i++) {
if (ch[j] == i) {
System.out.println("True");
result = true;
} else {
result = false;
}
}
}
return result;
}
public static void main(String args[]) {
System.out.println("Enter the string");
Scanner ob = new Scanner(System.in);
String s = ob.nextLine();
System.out.println(Digitinstring(s));
}
}
This code always gives the answer false. The if condition is not working.
What can I do to make it work properly?
Your code is failing because '3' does not equal 3. The character 3, which is your ch[j] will never be equal to an actual integer because they have different types. If you want this to work, you should replace your if condition with this:
Character.getNumericValue(ch[j]) == i;
An easier approach to this would be to simply use
Character.isDigit(s.charAt(j));
Your whole method would look like this:
public static boolean digitInString(String s){
for(int i = 0; i<s.length(); i++){
if(Character.isDigit(s.charAt(i))){
return true;
}
}
return false;
}
You can use regular expressions for more compact code. Regular expressions are good for exactly your scenario, which is looking for specific patterns in Strings. In your Digitinstring you can do the following:
return s.matches(".*\\d.*");
That returns true if your string has any number of characters (.*) followed by a digit (\\d) followed by any number of characters (.*). Any number of characters can include 0.
Swailem95's post well explains why your current implementation is not returning expected results.
/* Note: 48 to 57 is ascii values of 0,1, 2,...9 respectively
code is made more readable ascii values are not used now
*/
package com;
import java.util.Scanner;
public class Dis {
public static void main(String[] args) {
System.out.println("Enter the string");
Scanner ob = new Scanner(System.in);
String s = ob.nextLine();
System.out.println(Digitinstring(s));
ob.close();
}
private static boolean Digitinstring(String s) {
boolean result = false;
for (int j = 0; j < s.length(); j++) {
if(s.charAt(j)>='0' && s.charAt(j)<='9')
{
result=true;
break;
}
}
return result;
}
}
There are few problems. First is your else block. Remember that in case of if(){1}else{2} one of two blocks must always be executed, either it will be {1} or {2}.
It means that your result will depend only on last test, in other words on last character.
To solve this problem remove else block and let result store true only if your test will find digit.
Second problem is that, in (ch[j] == i) you are comparing char and int. So you are ending up with something like
if ('2' == 2) which is false in Java, because int representation of '2' is its index in Unicode Table, which is 50.
So as you see condition like '2'==2 is same as 50==2 which is false.
To generate all chars containing digits you can simply write for (char digit = '0'; digit<='9'; digit++) like in this code:
static boolean DigitInString(String s) {
for (char ch : s.toCharArray()) {
for (char digit = '0'; ch <= '9'; ch++) {
if (ch == digit) {
System.out.println("True");
return true;
}
}
}
return false;
}
You can also increase readability of your code and replace this nested loop
for (char digit = '0'; ch <= '9'; ch++) {
if (ch == digit) {
System.out.println("True");
return true;
}
}
with
if (Character.isDigit(ch)){
System.out.println("True");
return true;
}
This method will check if character is in range specified for digits characters in Unidoce Table.
You have a problem with:
for (i = 0; i <= 9; i++) {
if (ch[j] == i) {
System.out.println("True");
result = true;
} else {
result = false;
}
}
ch[j] is a character and i is a number, so the character '0' has a number value of 46 (if I remember correctly), so you can rectify the situation by adding '0' to i in the if statement
if (ch[j] == i+'0') {
or modifying the for loop
for (i = '0'; i <= '9'; i++) {
notice that the 0 in this case is a character.
if (ch[j] == i)
Please correct condition mentioned above to compare same object types, you currently using different types which is never true. Or use inbuilt isDigit method from Character Class.
I wrote this program for school and it almost works, but there is one problem. The goal of the program is to take an inputted string and create a new string out of each word in the input beginning with a vowel.
Example:
input: It is a hot and humid day.
output: Itisaand.
Here is the driver:
public class Driver {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String input = console.nextLine();
Class strings = new Class(input);
int beg=0;
for(int j=0;j<input.length();j++)
{
if(strings.isVowel(j)&&(j==0||input.charAt(j-1)==' '))
beg=j;
else if(strings.endWord(j)&&(beg==0||input.charAt(beg-1)==' '))
{
strings.findWord(beg, j);
}
}
System.out.print("Output: ");
strings.printAnswer();
}
}
And here is the class:
public class Class {
String input="",answer="";
public Class(String input1)
{
input = input1;
}
public boolean isVowel(int loc)
{
return (input.charAt(loc)=='U'||input.charAt(loc)=='O'||input.charAt(loc)=='I'||input.charAt(loc)=='E'||input.charAt(loc)=='A'||input.charAt(loc)=='a'||input.charAt(loc)=='e'||input.charAt(loc)=='i'||input.charAt(loc)=='o'||input.charAt(loc)=='u');
}
public boolean endWord(int loc)
{
return (input.charAt(loc)==' '||input.charAt(loc)=='.'||input.charAt(loc)=='?'||input.charAt(loc)=='!');
}
public void findWord(int beg,int end)
{
answer = answer+(input.substring(beg,end));
}
public void printAnswer()
{
System.out.println(answer+".");
}
}
With this code, i get the output:
Itisaa hotandand humidand humid summerand humid summer day.
By removing this piece of code:
&& (j == 0 || input.charAt(j-1) == ' ')
I get the proper output, but it doesn't work if an inputted word has more than one vowel in it.
For example:
input: Apples and bananas.
output: and.
Can someone please explain:
a) why the code is printing out words beginning with consonants as it is and
b) how I could fix it.
Also, the methods in the class I've written can't be changed.
Here's a better algorithm:
split the input into an array of words
iterate over each word
if the word begins with a vowel, append it to the output
The easiest way to split the input would be to use String.split().
Here's a simple implementation:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String input = console.nextLine();
String[] words = input.split(" ");
StringBuilder output = new StringBuilder();
for (String s : words) {
if (startsWithVowel(s)) {
output.append(s);
}
else {
output.append(getPunc(s));
}
}
System.out.println(output.toString());
}
public static boolean startsWithVowel(String s) {
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
char firstChar = s.toLowerCase().charAt(0);
for (char v : vowels) {
if (v == firstChar) {
return true;
}
}
return false;
}
public static String getPunc(String s) {
if (s.matches(".*[.,:;!?]$")) {
int len = s.length();
return s.substring(len - 1, len);
}
return "";
}
The problem with your code was:
It was counting the same word multiple times, due to it finding vowels and starting the word search process over again.
Heres how I went about solving the problem, while still keeping your code looking relatively the same: All I changed was your loop
for(int i=0;i<input.length();i++)
{
if(strings.isVowel(i) &&(i==0 || strings.endWord(i-1))){
beg = i;
for(int j = i; j < input.length();j++) //look for end of word
{
if(strings.endWord(j)) //word has ended
{
i = j; //start from end of last word
strings.findWord(beg, j);
break; //word done, end word search
}
}
}
}
As mentioned above, there are better ways to go about this, and there are some pretty glaring flaws in the setup, but you wanted an answer, so here you go
Normally i would suggest you where to fix your code, but it's seems there is a lot of bad code practice in here.
Mass Concatenation should be apply be StringBuilder.
Never call a class Class
Conditions are too long and can be shorten by a static string of Vowels and apply .contains(Your-Char)
Spaces, Indentations required for readability purposes.
A different way of attacking this problem, may probably accelerate your efficiency.
Another approch will be Split the code by spaces and loop through the resulted array for starting vowels letters and then Append them to the result string.
A better readable and more maintainable version doing what you want:
public static String buildWeirdSentence(String input) {
Pattern vowels = Pattern.compile("A|E|I|O|U|a|e|i|o|u");
Pattern signs = Pattern.compile("!|\\.|,|:|;|\\?");
StringBuilder builder = new StringBuilder();
for (String word : input.split(" ")) {
String firstCharacter = word.substring(0, 1);
Matcher vowelMatcher = vowels.matcher(firstCharacter);
if (vowelMatcher.matches()) {
builder.append(word);
} else {
// we still might want the last character because it might be a sign
int wordLength = word.length();
String lastCharacter = word.substring(wordLength - 1, wordLength);
Matcher signMatcher = signs.matcher(lastCharacter);
if (signMatcher.matches()) {
builder.append(lastCharacter);
}
}
}
return builder.toString();
}
In use:
public static void main(String[] args) {
System.out.println(buildWeirdSentence("It is a hot and humid day.")); // Itisaand.
}
I think best approach is to split input and then check each word if it starts with vowel.
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String str = console.next();
String[] input = str.split(" ");
StringBuilder s = new StringBuilder();
String test;
for (int i = 0; i < input.length; i++)
{
test = input[i];
if (test.charAt(0) == 'U' || test.charAt(0) == 'O'
|| test.charAt(0) == 'I' || test.charAt(0) == 'E'
|| test.charAt(0) == 'A' || test.charAt(0) == 'a'
|| test.charAt(0) == 'e' || test.charAt(0) == 'i'
|| test.charAt(0) == 'o' || test.charAt(0) == 'u')
{
s.append(input[i]);
}
}
System.out.println(s);
}
The problem with your code is that you override the first beg when a word has more that vowel. for example with Apples beg goes to 0 and before you could call findWord to catch it, it gets overridden with 4 which is the index of e. And this is what screws up your algorithm.
You need to note that you have already found a vowel until you have called finWord, for that you can add a boolean variable haveFirstVowel and set it the first time you have found one to true and only enter the branch for setting that variable to true if you haven't already set it. After you have called findWord set it back to false.
Next you need to detect the start of a word, otherwise for example the o of hot could wrongly signal a first vowel.
Class strings = new Class(input);
int beg = 0;
boolean haveFirstVowel = false;
for (int j = 0; j < input.length(); j++) {
boolean startOfWord = (beg == 0 || input.charAt(j - 1) == ' ');
if (startOfWord && ! haveFirstVowel && strings.isVowel(j)) {
beg = j;
haveFirstVowel = true;
}
else if (strings.endWord(j) && haveFirstVowel) {
strings.findWord(beg, j);
haveFirstVowel = false;
}
}
System.out.print("Output: ");
strings.printAnswer();
I think overall the algorithm is not bad. It's just that the implementation can definitely be better.
Regarding to the problem, you only need to call findWord() when:
You have found a vowel, and
You have reached the end of a word.
Your code forgot the rule (1), therefore the main() can be modified as followed:
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String input = console.nextLine();
Class strings = new Class(input);
int beg = 0;
boolean foundVowel = false; // added a flag indicating whether a vowel has been found or not
for (int j = 0; j < input.length(); j++) {
if (strings.isVowel(j) && (j == 0 || input.charAt(j - 1) == ' ')) {
beg = j;
foundVowel = true;
} else if (strings.endWord(j) && (beg == 0 || input.charAt(beg - 1) == ' ')) {
if (foundVowel) { // only call findWord() when you have found a vowel and reached the end of a word
strings.findWord(beg, j);
foundVowel = false; // remember to reset the flag
}
}
}
System.out.print("Output: ");
strings.printAnswer();
I've spend the day working on these two classes. I've come further than I was expecting to yet needless to say I'm running into issues.
Basically I have to take an inputted String and return only the uppercase letters, every second letter, the entire string but with all vowels exchanged with an underscore, number of vowels in the string, and lastly positions of all vowels in the string.
I specifically designed my tester class, I believe correctly, to have a menu to try each command separately so I'm able to test each one.
This is the tester class..
//******************************************
// LetterTest.java
// Written by Sanchez
// 2013
//*******************************************
//===========================================
// This program tests the CharAPI class.
//===========================================
import java.util.Scanner;
public class LetterTest {
public static void main(String[] args){
//create Scanner for user input
Scanner in = new Scanner(System.in);
//get user input
System.out.println("Please enter a string of letters");
String input = in.nextLine();
System.out.println("\nChoose an option: "
+"\n1 - Uppercase, "
+"\n2 - Every Second Letter, "
+"\n3 - Replace vowels "
+"\n4 - Number of vowels "
+"\n5 - Positions of vowels");
int choice = in.nextInt();
//Call the method based on user choice
if (choice == 1) {
//each method returns a String
System.out.println(LetterAPI.bigLetters(input) );
}
else if (choice ==2) {
System.out.println(LetterAPI.secondLetter(input) );
}
else if (choice ==3) {
System.out.println(LetterAPI.vowelsGone(input) );
}
else if (choice ==4) {
System.out.println(LetterAPI.vowelNumber(input) );
}
else {
System.out.println(LetterAPI.vowelPositions(input) );
}
}
}
That seems to be working pretty well and I'm happy with it.
The issue I'm having is in my class with the objects that do the manipulation
I've used the // on a couple things just so I could get it to compile. The 1st, 2nd, and 4th, straight up don't return anything. The third one only exchanges the last letter for an underscore even if it's not a vowel, and the fifth one works pretty well except I'd like to add 1 to all the numbers so the results start at 1 and not 0. I understand that there's a lot going on here but I've spent the day on it and am finally submitting that I am in dire need of help.
This is the code for the objects...
//******************************************
// LetterAPI.java
// Written by Sanchez
// 2013
//*******************************************
//===========================================
// Objects of this class manipulate an inputted string.
//===========================================
import java.util.Scanner;
//contains a set of methods for maniuplaing the string
public class LetterAPI {
//print only uppercase letters
public static String bigLetters(String input) {
String result = "";
for (int i = 0; i <input.length(); i++) {
char currentLetter=input.charAt(i);
if (Character.isUpperCase(currentLetter))
result = result;
}
return result;
}
//print every second letter
public static String secondLetter(String input) {
String result = "";
for (int i = 0; i <input.length(); i++) {
//result = input.charAt(input);
}
return result;
}
//all vowels replaced by underscores
public static String vowelsGone(String input) {
String result ="aeiouAEIOU";
for (int i = 0; i<result.length();i++) {
result=input.replace(result.charAt(i), '_');
}
return result;
}
//the numbers of vowels
public static String vowelNumber(String input) {
String result = "";
for (int i = 0; i <input.length(); i++) {
if (Character.toLowerCase(input.charAt(i)) == 'a' || Character.toLowerCase(input.charAt(i)) == 'e' || Character.toLowerCase(input.charAt(i)) == 'i' || Character.toLowerCase(input.charAt(i)) == 'o' || Character.toLowerCase(input.charAt(i)) == 'u') {
i++;
}
}
return result;
}
//the positions of all vowels
public static String vowelPositions(String input) {
String result = "";
for (int i = 0; i <input.length(); i++) {
if (Character.toLowerCase(input.charAt(i)) == 'a' || Character.toLowerCase(input.charAt(i)) == 'e' || Character.toLowerCase(input.charAt(i)) == 'i' || Character.toLowerCase(input.charAt(i)) == 'o' || Character.toLowerCase(input.charAt(i)) == 'u') {
result = result + i + " ";
}
}
return result;
}
}
===UPDATE===
Thank you everyone! I've made some progress thank god. I've gotten the 3rd and 4th to work great. The first one was giving only the last uppercase but now is repeating my input. The second one is just giving me back the 1st letter. As for the last one I tried parenthesis but I seemed to have broke it so I put it back for now. That's not as critical..at least it works! If I can't figure that out I'll have to put a note that the count starts at 0. But the first two are killing me..at least it compiles. Here's where I'm at so far...
//******************************************
// LetterAPI.java
// Written by Sanchez
// 2013
//*******************************************
//===========================================
// Objects of this class manipulate an inputted string.
//===========================================
import java.util.Scanner;
//contains a set of methods for maniuplaing the string
public class LetterAPI {
//print only uppercase letters
public static String bigLetters(String input) {
String result = "";
char cl;
for (int i = 0; i <input.length(); i++) {
cl=input.charAt(i);
if (Character.isUpperCase(cl))
input = input + cl;
}
return input;
}
//print every second letter
public static String secondLetter(String input) {
String result = "";
for (int i=0; i<input.length(); i+=2) {
input = input + input.charAt(i) + " ";
}
return input;
}
//all vowels replaced by underscores
public static String vowelsGone(String input) {
String vowels ="aeiouAEIOU";
for (int i = 0; i<vowels.length();i++) {
input=input.replace(vowels.charAt(i), '_');
}
return input;
}
//the numbers of vowels
public static String vowelNumber(String input) {
String result = "";
int count = 0;
for (int i = 0; i <input.length(); i++) {
if (Character.toLowerCase(input.charAt(i)) == 'a' || Character.toLowerCase(input.charAt(i)) == 'e' || Character.toLowerCase( input.charAt(i)) == 'i' || Character.toLowerCase(input.charAt(i)) == 'o' || Character.toLowerCase(input.charAt(i)) == 'u') {
count++;
result = count + " ";
}
}
return result;
}
//the positions of all vowels
public static String vowelPositions(String input) {
String result = "";
for (int i = 0; i <input.length(); i++) {
if (Character.toLowerCase(input.charAt(i)) == 'a' || Character.toLowerCase(input.charAt(i)) == 'e' || Character.toLowerCase(input.charAt(i)) == 'i' || Character.toLowerCase(input.charAt(i)) == 'o' || Character.toLowerCase(input.charAt(i)) == 'u') {
result = result + i + " ";
}
}
return result;
}
}
Hints:
In part 1, you do this: result = result; That is nonsensical. It does nothing.
In part 2, the compilation error is because you are trying to assign a char to a String. That's not legal. But it is also not what you should be trying to do. (Think "append", not "assign" ...)
In part 3, the first mistake is this: String result = "aeiouAEIOU";. In fact, it should be String result = input;.
In part 4, you are counting all vowels, not each different vowel. You also need to turn the count (or counts) into a String (in result).
About part 5 you say: "works pretty well except I'd like to add 1 to all the numbers". So do it!