Everytime i input my sentence it prints out the outcome each time it goes through the loop. i assume i have to put the printlines outside the loop?
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
System.out.println("There are " + count + " vowels in this string");
}
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
System.out.println("The vowels are: " + empty);
}
}
}
}
import java.util.*;
public class homework4{
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty= "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
No need to check condition two times. As you are updating variables (count & empty) in loop, have to print only once after exiting from loop.
you just need to move the print statement outside and put a check condition if the count is still zero then it means there were no vowels and if count is not zero you can print it.
import java.util.Scanner;
public class homework4 {
public static void main(String[] args) {
//Scanner
Scanner keyBd = new Scanner(System.in);
System.out.println("Enter a sentence ");
String userIn = keyBd.nextLine();
int count = 0;
String empty = "";
//Code
for (int i = 0; i < userIn.length(); i++) {
char ch = userIn.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
empty += ch + " ";
}
}
if(count == 0){
System.out.println("There are no vowels in the input string");
}else {
System.out.println("There are " + count + " vowels in this string");
System.out.println("The vowels are: " + empty);
}
}
}
You don't need to test for vowels twice? (and add to count twice), only once:-
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
count++;
empty += ch + " ";
}
And your print statement doesn't need to happen every time you find a vowel:-
for (int i = 0; i < userIn.length(); i++) {
// not in here
}
System.out.println("There are " + count + " vowels in this string\n" + "The vowels are: " + empty);
Additionally...
If statements are ugly here, where there are many conditions. A switch would be easier to read and more efficient:-
switch (ch){
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
count++;
empty += ch + " ";
break;
}
Or move the whole condition into a method
public boolean isVowel(char c){
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');
}
and use
if (isVowel(ch)){
//...
}
Related
I am trying to write a method that will take a string, convert any letters to an int, and return all the converted ints to main, replacing the letters . I have if statements that convert all the letters to numbers, but I am having trouble making it work with a loop to convert all the letters instead of stopping after the first one. Any help would be appreciated, thanks in advance.
public class PhoneNumberChecker
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the phone number
System.out.print("Phone number to convert: ");
String phoneNumber = input.nextLine();
// Process each character in the phone number for display
for (int i = 0; i < phoneNumber.length(); ++i)
{
// Get the character
char ch = phoneNumber.charAt(i);
if (Character.isLetter(ch))
ch = (Character.toUpperCase(ch));
else
System.out.print(ch);
}
System.out.println(getNumber(phoneNumber));
input.close();
// end method
}
public static String getNumber(String phoneNumber)
{
for (int i = 0; i < phoneNumber.length(); ++i)
{
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
return "2";
else if
(ch == 'D' || ch == 'E' || ch == 'F')
return "3";
else if
(ch == 'G' || ch == 'H' || ch == 'I')
return "4";
else if
(ch == 'J' || ch == 'K' || ch == 'L')
return "5";
else if
(ch == 'M' || ch == 'N' || ch == 'O')
return "6";
else if
(ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S')
return "7";
else if
(ch == 'T' || ch == 'U' || ch == 'V')
return "8";
else if
(ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z')
return "9";
}
return "";
}
}
You want to append the string results to a string that will continue to grow as you iterate over the given phone number.
Create a String variable before your loop, then simply append to that string instead of returning the strings. Then once you're done iterating the phone number you can return the String.
public static String getNumber(String phoneNumber){
String convertedNum = "";
for (int i = 0; i < phoneNumber.length(); ++i)
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
convertedNum = convertedNum + "2"; //append to the string
else if(ch == 'D' || ch == 'E' || ch == 'F')
convertedNum = convertedNum + "3";
...
return convertedNum; //then return it at the end
}
You return from the method after the first character was handled. Let's modify your method:
public static String getNumber(String phoneNumber, int i)
{
//for (int i = 0; i < phoneNumber.length(); ++i)
{
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
return "2";
else if
(ch == 'D' || ch == 'E' || ch == 'F')
return "3";
else if
(ch == 'G' || ch == 'H' || ch == 'I')
return "4";
else if
(ch == 'J' || ch == 'K' || ch == 'L')
return "5";
else if
(ch == 'M' || ch == 'N' || ch == 'O')
return "6";
else if
(ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S')
return "7";
else if
(ch == 'T' || ch == 'U' || ch == 'V')
return "8";
else if
(ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z')
return "9";
}
return "";
}
Note, that it has an int parameter and the cycle was commented out. Now, let's process a String:
public static function parseString(String input) {
String output = "";
for (int i = 0; i < input.length; i++) {
output += getNumber(input, i);
}
return output;
}
Note, that this is very simple to understand. The thing which makes it simple is the fact that a method is doing a single thing. getNumber gets a number from a String at a given index. parseString parses the String in the way your code suggested. Of course you can modify the initial String if that is the purpose, using setChar, but then the getNumber method should return the char representation of the digits.
As an alternative you could use String.relaceAll instead of checking each char in a nested if-else. Example:
public static String getNumber(String phoneNumber){
String result = phoneNumber.toUpperCase()
.replaceAll("[A-C]", "2")
.replaceAll("[D-F]", "3")
.replaceAll("[G-I]", "4")
.replaceAll("[J-L]", "5")
.replaceAll("[M-O]", "6")
.replaceAll("[P-S]", "7")
.replaceAll("[T-V]", "8")
.replaceAll("[X-Z]", "9");
return result;
}
I would suggest you to use StringBuilder as compared to String as it is preferable performance wise compared to String. The reason is String is immutable. So inside the loop the String object will be created again and again. Whereas StringBuilder is mutable so it is declared only once and then can be operated on by it's reference. You can use it as shown below:
public static String getNumber(String phoneNumber){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < phoneNumber.length(); ++i){
char ch = phoneNumber.charAt(i);
ch = Character.toUpperCase(ch);
if (ch == 'A' || ch == 'B' || ch == 'C')
sb.append("2");
else if(ch == 'D' || ch == 'E' || ch == 'F')
sb.append("2");
else if(ch == 'G' || ch == 'H' || ch == 'I')
sb.append("3");
else if(ch == 'J' || ch == 'K' || ch == 'L')
sb.append("4");
else if(ch == 'M' || ch == 'N' || ch == 'O')
sb.append("5");
}
return sb.toString();
}
You can read about performance of String vs StringBuilder here. Pay attention to switch from concatination(+) to Builder.
This program takes in a statement and then print the number of vowels, numerics, etc. I wanted to know how I could print the list of numerics and vowels which have been given as input.
Can someone tell me how this could be done using an array?
package strings;
import java.util.Scanner;
public class Strings
{
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a statement:");
String statement = sc.nextLine().toLowerCase();
System.out.println("------------------------------------------------");
System.out.println("Total characters: " + statement.length());
int vowels = 0,num = 0,spaces = 0,spl = 0,others = 0;
char alpha;
for (int i = 0;i < statement.length();i++)
{
alpha = statement.charAt(i);
if (alpha == 'a' || alpha == 'e' || alpha == 'i' || alpha == 'o' || alpha == 'u')
{
vowels++;
}
else if (alpha == ' ')
{
spaces++;
}
else if (alpha == '0' || alpha == '1' || alpha == '2' || alpha == '3' || alpha == '4' || alpha == '5' || alpha == '6' || alpha == '7' || alpha == '8' || alpha == '9')
{
num++;
}
else if (alpha =='!' || alpha =='#' || alpha =='#' || alpha =='$' || alpha =='%' || alpha =='^' || alpha =='&' || alpha =='*' || alpha =='(' || alpha ==')')
{
spl++;
}
else
{
others++;
}
}
System.out.println("Total vowels: " + vowels);
System.out.println("Total spaces: " + spaces);
System.out.println("Total numerics: " + num);
System.out.println("Total special characters: " + spl);
System.out.println("Other characters: " + others);
System.out.println("");
for (int i = 0;i < statement.length();i++)
{
System.out.println("The vowels are as follows:");
System.out.println(alpha);
}
}
}
You can use java.util.ArrayList, for example, create an ArrayList for vowels:
List<Character> vowelList = new ArrayList<>();
...
for (int i = 0; i < statement.length(); i++) {
if (alpha == 'a' || alpha == 'e' || alpha == 'i' || alpha == 'o' || alpha == 'u') {
vowels++;
vowelList.add(alpha);
} else {
...
}
System.out.println("The vowels are as follows:");
System.out.println(vowelList);
If in case you don't want to use any external packages.
....
Character v[] = new Character[statement.length()];
....
if (alpha == 'a' || alpha == 'e' || alpha == 'i' || alpha == 'o' || alpha == 'u'){
v[vowels++] = alpha;
}
....
System.out.println("The vowels are as follows:");
for (Character c : v) {
if (c != null) {
System.out.println(c);
}
}
this is the program can anyone help me
at first i have given the string first part is working fine it finds the vowels in string and it prints
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "History can also refer to the academic discipline ";
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u'
|| a.charAt(i) == 'u') {
System.out.println("The sentence have vowels:" + a.charAt(i));
count++;//counting the number of vowels
}
if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u'
|| a.charAt(i+1) == 'u') {i++;}//finding reoccurring vowels
}
System.out.println("number of vowels:" + count);
}
}
in second part im trying to skip the reoccurring vowels but its not working
You need to make a couple of changes:
Run the loop till a.length() - 1 as you are already checking for i+1st character inside the loop
Reset the count if the second if condition is not satisfied.
e.g.:
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "History can also refer to the academic discipline ";
int count = 0;
for (int i = 0; i < a.length() - 1; i++) {
if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'u'
|| a.charAt(i) == 'u') {
System.out.println("The sentence have vowels:" + a.charAt(i));
count++;//counting the number of vowels
}
//finding reoccurring vowels
if (a.charAt(i+1) == 'a' || a.charAt(i+1) == 'e' || a.charAt(i+1) == 'i' || a.charAt(i+1) == 'u'
|| a.charAt(i+1) == 'u') {
i++;
} else{
count = 0;
}
}
System.out.println("number of vowels:" + count);
}
How about this
public static void main(String[] args) {
String a = "History can also refer to the academic discipline ";
int count = 0;
boolean lastWasVowel = false;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == 'a' || a.charAt(i) == 'e' || a.charAt(i) == 'i' || a.charAt(i) == 'o'
|| a.charAt(i) == 'u') {
if(!lastWasVowel) {
count++;
}
lastWasVowel = true;
} else {
lastWasVowel = false;
}
}
System.out.println("number of vowels:" + count);
}
public class vowel {
public static void main(String args[])
{
String sentence;
int vowels = 0, digits = 0, blanks = 0, consonants=0;
char ch;
System.out.print("Enter a String : ");
sentence = TextIO.getln();
sentence = sentence.toLowerCase();
for(int i = 0; i < sentence.length(); i ++)
{
ch = sentence.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels ++;
else if(ch =='b'|| ch == 'c' || ch == 'd'|| ch =='f' || ch =='g' ||
ch == 'h' || ch =='j' || ch =='k'|| ch =='l' || ch =='m' ||
ch == 'n' || ch =='p' || ch =='q'|| ch =='r' || ch =='s' ||
ch == 't' || ch =='v' || ch =='w'|| ch =='x' || ch =='z' ||
ch == 'y')
consonants ++;
else if(Character.isDigit(ch))
digits ++;
else if(Character.isWhitespace(ch))
blanks ++;
}
System.out.println("Vowels : " + vowels);
System.out.println("Consonants : " +consonants);
System.out.println("Digits : " + digits);
System.out.println("Blanks : " + blanks);
}
}
This program works perfectly in counting, but I wish to add on a function display the word it count
For example, input ABBCC12:
Vowels :1
Input Vowels : A
Consonants :4
Input Consonants : BBCC
Digits :2
Input Digits :12
Can I know what to do next?
Thanks in advance
It looks as though the easiest way that would fit with your current way of working would be to keep hold of a StringBuilder for each type:
vowelsStringBuilder = new StringBuilder();
and then whenever you encounter one, you add it on:
vowelsStringBuilder.append(ch);
At the end, you can then use
String vowelsString = vowelsStringBuilder.toString();
to get the final String containing all the vowels.
In fact, if you do it like this, you don't really need to count them as you go, because you can get the number of vowels at the end with vowelsString.length().
I'm super new to programming so I would love to keep this simple. The compiler accepts my code, but when I run the program and type in for example the letter A I just get a ton of errors. I tried earlier using String letter instead of int letter, but I just got compiler errors stating I couldn't convert Strings to characters or something. I'm really confused and could use a quick explanation and fix so I can get a number back. Here's my code:
import java.util.Scanner;
import java.lang.String;
public class PhoneAlgorithm {
public static void main(String[] args){
int digit = -1;
Scanner in;
in = new Scanner(System.in);
System.out.print("Enter an uppercase letter to find out the corresponding digit on a telephone: ");
int letter;
letter = Integer.parseInt(in.next());
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = 2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = 3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = 4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = 5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = 6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = 7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = 8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = 9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
if (digit != -1) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}
When you use parseInt(str), you will get an Exception if the parameter str cannot be converted to an integer.
You must use char, since you are comparing the input with single characters:
char letter;
letter = in.nextLine().charAt(0);
str.charAt(index) Returns the char value at the specified index.
I have modified your code, I guess this is what you are looking for..
import java.util.Scanner;
public class Try {
public static void main(String[] args) {
//declarations
char letter;
int digit=0;
// Asking the user to enterstring
System.out.println("Enter the string");
String enterString;
//creating a scanner object and reading the string
Scanner input = new Scanner(System.in);
enterString= input.next();
System.out.println("Entered string is "+enterString);
int temp=0;
for(int i=0;i<enterString.length();i++){
letter=(char)enterString.codePointAt(i);
if (letter == 'A' || letter == 'B' || letter == 'C') {
digit = digit*10+2; }
else if (letter == 'D' || letter == 'E' || letter == 'F') {
digit = digit*10+3; }
else if (letter == 'G' || letter == 'H' || letter == 'I') {
digit = digit*10+4; }
else if (letter == 'J' || letter == 'K' || letter == 'L') {
digit = digit*10+5; }
else if (letter == 'M' || letter == 'N' || letter == 'O') {
digit = digit*10+6; }
else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S') {
digit = digit*10+7; }
else if (letter == 'T' || letter == 'U' || letter == 'V') {
digit = digit*10+8; }
else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z') {
digit = digit*10+9; }
else if (letter >= 'a' && letter >= '3') {
System.out.print("You did not enter a valid uppercase letter. Try again!");
}
/*if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}*/
}
if (digit != 0) {
System.out.println("The corresponding digit on your telephone is: " + digit);
}
}
}