I'm trying to make a program that counts the number of vowels in a sentence, but for some reason my for-loop keeps iterating by 2 (figured this out by printing out the value of i during each iteration). What's wrong with it?
//input
Scanner input = new Scanner(System.in);
String sentence;
//prompt
System.out.print("Type a sentence. \nThe number of vowels will be counted.");
sentence = input.nextLine();
//vowel check
int charcount = 0;
String temp;
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i++);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
System.out.print("There are " + charcount + " vowels in your sentence.");
}
}
Change this line to:
temp = sentence.substring(i, i+1);
If you do i++ it will increment the value of i.
i++ is equivalent to i = i + 1;
There are two times when you're incrementing i , once in your for loop definition, and once in your sentence.substring
Any time you put i++ the variable i will be increased by 1, regardless of it being in the for loop's definition or in another part of the loop.
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i+1);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
Should work.
Also, and someone who is more familiar with java than I am can correct me on this if I'm mistaken, but temp.equalsIgnoreCase() returns a boolean, so you don't need to do == True, you can just write else if (temp.equalsIgnoreCase("u"))
Addition: As per Scary Wombat's comment, you could simplify this even more so, as so:
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i+1);
if (temp.equalsIgnoreCase("a") || temp.equalsIgnoreCase("e") ||
temp.equalsIgnoreCase("i") || temp.equalsIgnoreCase("o") ||
temp.equalsIgnoreCase("u"))
charcount ++;
}
You have two instances of i++. Each is equivalent to i=i+1. You probably want your second one to be (i+1) rather than i++.
I suggest you don't use the substring method as it creates a new string from the original string.
From the documentation:
String substring(int beginIndex)
Returns a new string that is a substring of this string.
Instead, use the charAt method which returns the character value at the specified index.
You can also cleanup the implementation by using a string with the vowels and invoking the indexOf method on it to test if the character in question is a vowel or not. Below is an example:
String vowels = "aeiou";
sentence = sentence.toLowerCase();
for (int i = 0; i < sentence.length(); i++) {
char letter = sentence.charAt(i);
if (vowels.indexOf(letter) > -1) {
charCount++;
}
}
Related
In java, I am suppose to examine each character in the sentence, from left to right and count the number of identical characters to its right and print the count.
Scanner K = new Scanner(System.in);
String s = K.nextLine();
for (int i = 0; i < s.length(); i++) {
int count = 0;
while (i+1 < s.length() && s.charAt(i)== s.charAt(i + 1))
{
i++;
count++;
}
System.out.print(s.charAt(i)+ ":");
System.out.println(count);
}
System.out.println();
}
}
Example output should be like:(when i input "I love u")
I:0
: 1
l:0
o:0
v:0
e:0
:0
u:1
I'm trying to count the number of occurrences of letters that are in string. The code that I have written technically does what I want, but not the way I want to do it. For example, if I input "Hello World", I want my code to return "a=0 b=0 c=0 d=0 e=1 etc...." with the code I have written it returns "H=1, e=1, l=2 etc...."
Also how would I make sure that it is not case sensitive and it doesn't count spaces.
Code:
import java.util.Scanner;
public class Sequence {
private static Scanner scan = null;
public static void main(String[] args) {
scan = new Scanner(System.in);
String str = null;
System.out.print("Type text: ");
str = scan.nextLine();
int[] count = new int[255];
int length = str.length();
for (int i = 0; i < length; i++)
{
count[str.charAt(i)]++;
}
char[] ch = new char[str.length()];
for (int i = 0; i < length; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
{
System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");
}
}
}
}
As I hinted in my original comment you only need an array of 26 int(s) because there are only 26 letters in the alphabet. Before I share the code, it is important to note that Java char is an integral type (and, for example, 'a' + 1 == 'b'). That property is important, because it allows you to determine the correct offset in an array (especially if you force the input to lower case). Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
}
System.out.println();
If you really want to see all of the letters that have counts of zero (seems pointless to me), change
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
to remove the if and just
System.out.printf("%c=%d ", 'a' + i, count[i]);
Change str = scan.nextLine(); to str = scan.nextLine().toLowerCase().replaceAll("\\s+","");
.toLowerCase() is a method which makes every char in the string lowercase.
.replaceAll() is a method which replaces one char with another. In this case, it replaces whitespaces with nothing.
My Question would be how can replace every 3rd ';' from a String a put a ',' at this position ?
for eg.:
String s = "RED;34;34;BLUE;44;44;GREEN;8;8;BLUE;53;53"
so that the String looks like:
RED;34;34,BLUE;44;44,GREEN;8;8,BLUE;53;53
I tried to solve it like this but i can't take a charAt(i) and replace it with an other char.
int counter =0;
for (int i=0;i<s.length();i++){
if(s.charAt(i) == ';'){
counter++;
}
if(counter ==3){
s.charAt(i)=',';
counter =0;
}
}
Normally some own effort is demanded from the question, but regex is hard.
s = s.replaceAll("([^;]*;[^;]*;[^;]*);", "$1,");
A sequence of 0 or more of not-semicolon followed by semicolon and such.
[^ ...characters... ] is some char not listed.
...* is zero or more of the immediately preceding match.
The match of the 1st group (...) is given in $1, so actually only the last semicolon is replaced by a comma.
You can use the modulo % operator to know the 3rd time something occurs. And a simple conversion between string and char array to do the rest:
class Main {
public static void main(String[] args) {
String s1 = "RED;34;34;BLUE;44;44;GREEN;8;8;BLUE;53;53";
char [] s = s1.toCharArray();
int j=0;
for(int i=0;i<s.length;i++){
if (s[i]==';') {
j++;
if(j % 3 == 0) {
s[i] = ',';
}
}
}
System.out.println(s);
}
}
There are many ways to do it, as I suggested in a comment. Here are implementations of the ones I suggested, but there are of course more ways than this.
The first is the simplest, from a code point of view, if you know regex. See answer by Joop Eggen for an explanation.
The second is likely the fastest, especially if you eliminate the % modulo operator by resetting j to 0 instead.
private static String usingRegex(String s) {
return s.replaceAll("([^;]*;[^;]*;[^;]*);", "$1,");
}
private static String usingCharArray(String s) {
char[] arr = s.toCharArray();
for (int i = 0, j = 0; i < arr.length; i++)
if (arr[i] == ';' && ++j % 3 == 0)
arr[i] = ',';
return new String(arr);
}
private static String usingStringBuilder(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0, j = 0; i < sb.length(); i++)
if (sb.charAt(i) == ';' && ++j % 3 == 0)
sb.setCharAt(i, ',');
return sb.toString();
}
private static String usingSubstring(String s) {
int i = -1, j = 0;
while ((i = s.indexOf(';', i + 1)) != -1)
if (++j % 3 == 0)
s = s.substring(0, i) + ',' + s.substring(i + 1);
return s;
}
Test
String s = "RED;34;34;BLUE;44;44;GREEN;8;8;BLUE;53;53";
System.out.println(usingRegex(s));
System.out.println(usingCharArray(s));
System.out.println(usingStringBuilder(s));
System.out.println(usingSubstring(s));
Output
RED;34;34,BLUE;44;44,GREEN;8;8,BLUE;53;53
RED;34;34,BLUE;44;44,GREEN;8;8,BLUE;53;53
RED;34;34,BLUE;44;44,GREEN;8;8,BLUE;53;53
RED;34;34,BLUE;44;44,GREEN;8;8,BLUE;53;53
Not that elegant like by #Joop, but probably simplier to understand:
String s = "RED;34;34;BLUE;44;44;GREEN;8;8;BLUE;53;53";
char[] chars = s.toCharArray();
int counter = 1;
for (int i = 0; i < chars.length; i++){
if (chars[i] == ';'){
if (counter == 3){
chars[i] = ','; // replace ';' with ','
counter = 1; // set counter to 1
}else {
counter++;
}
}
}
String output = String.valueOf(chars);
System.out.println(output); // RED;34;34,BLUE;44;44,GREEN;8;8,BLUE;53;53
I'm doing an assignment and I am done. This is a simple program that prints out pyramids of chars. However, I can't figure out why the program prints a newline when I never specified it with some input, even if it's meant to: https://i.imgur.com/gPs5oC5.png
Why do I have to have an extra newline when printing the pyramid upside down? Where is the newline printed?
import java.util.Scanner;
public class Test23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean state = true;
String messageL = "Length: ";
String messageD = "Position: ";
String messageS = "Shutdown!";
while(state) {
int limit = 0;
int degree;
System.out.print(messageL);
int length = input.nextInt();
while ((length < 1 && length == -1) || length > 26) {
if (length == -1 ) {
System.out.println(messageS + "\n");
state = false;
break;
} else {
System.out.print(messageL);
length = input.nextInt();
}
}
if (!state)
break;
System.out.print(messageD);
degree = input.nextInt();
while((degree > 1) || (degree < 0)) {
System.out.print(messageD);
degree = input.nextInt();
}
if (degree == 0)
//No newline is needed here for some reason.
length++;
else if (degree == 1)
limit = length;
//New line here for the pyramids to print symmetrically.
//System.out.println("");
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
System.out.print(letter);
}
if (degree == 0)
limit++;
else if (degree == 1)
limit--;
System.out.println("");
}
System.out.println("");
}
}
}
Small java program prints invisible newline?
In your program the last System.out.println(""); causes an extra line at the end of your program, i.e while(state) is true at the end, So either you comment the print statement or make your state=false at end.
while(state) {
...
System.out.println("");
}
The most inner loop won't run if the input is 0. limit will be 0, and hence the loop condition is false. As of this it will print en empty line, proceeding to add 1 too limit and then print chars.
for (int i = 0; i < length; ++i) {
for (int counter = 0; counter < limit; counter++) {
char letter = (char)(counter + 'A');
I'm working on this program where I need to verify if every odd index in a String has the letter "X". For example if my String is: AXFXTX then I should get a message: "GOOD", if not I should get a message: "BAD". Can anyone tell me what I'm missing please. Thank you in advanced.
Here's my code
import java.util.Random;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new Scanner(System.in);
int min = 1;
int max = 10;
int randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println("Random number = " + randomNum);
System.out.print("Enter a word of " + randomNum + " characters:");
String myString = scan.nextLine();
while(myString.length() != randomNum){
System.out.print("Enter a word of " + randomNum + " characters:");
myString = scan.nextLine();
}
char[] c = myString.toCharArray();
for(int i = 0 ; i < c.length ; i++){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}
}
If I understand your question, then it's important to note that the first odd index is 1. So you can start at 3 and check if that, and every subsequent odd number (index += 2), is the same as the first. Something like,
boolean sameLetter = true;
for (int index = 3; index < c.length && sameLetter; index += 2) {
sameLetter = (c[1] == c[index]);
}
System.out.println(sameLetter ? "GOOD!" : "BAD");
Simply evaluate odd indices only:
char[] c = myString.toCharArray();
boolean good = true;
for(int i = 3 ; i < c.length ; i+=2){
if(c[i] != c[i-2]){
good = false;
break;
}
}
if(good) System.out.println("GOOD");
else System.out.println("BAD");
I would simply use a regular expression here
str.matches(".(\\w)(.\\1)+") //true is GOOD
Try
booelan allGood = true;
for(int i = 2 ; i < c.length ; i = i + 2){
if(c[i] != c[0]){
allGood = false;
break;
}
}
To start with, you need a boolean variable here to track if it's consistent across all characters. Second, you need to improve your loop
boolean testSucceed = true;
for(int i = 1 ; i < c.length ; i += 2){
if (c[i] != 'X') testSucceed = false;
break;
}
if(testSucceed){
System.out.println("GOOD!");
} else{
System.out.println("BAD");
}
Change the for loop to :
for(int i = 0 ; i < c.length ; i+=2)
so that it goes over alternate characters.
//If NOT divisible by 2- Check only ODD number
Edited: You are suppossed to use modulus % and not division %. My bad
for(int i = 0 ; i < c.length ; i++){
if(c[i]%2 != 0){
if(c[i] == 'X'){
System.out.println("GOOD!");
}
else{
System.out.println("BAD");
}
}
}