For loop is printing out multiple print statements - java

I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}

You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)

Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2

Related

replace all underscores (if any) with vowels present in the string

You are given a string s consisting of lowercase English letters
and/or '_' (underscore). You have to replace all underscores (if any)
with vowels present in the string.
The rule you follow is: Each underscore can be replaced with any one
of the vowel(s) that came before it.
You have to tell the total number of distinct strings we can generate
following the above rule.
My code is giving wrong output on some input
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
int a=0,e=0,i1=0,o=0,u=0;
int ans = 1;
for(int j=0;j<Integer.parseInt(test);j++){
String s = sc.nextLine();
// System.out.println(s);
for(int i=0;i<s.length();i++){
if( s.charAt(i)=='a' || s.charAt(i)=='o' || s.charAt(i)=='i' || s.charAt(i)=='e' || s.charAt(i)=='u' ) {
if(s.charAt(i)=='a')
a=1;
else if(s.charAt(i)=='e')
e=1;
else if(s.charAt(i)=='i')
i1=1;
else if(s.charAt(i)=='o')
o=1;
else if(s.charAt(i)=='u')
u=1;
}
else if(s.charAt(i)=='_'){
int sum = a + e +i1 +o + u;
if(sum != 0)
ans = ans * sum;
}
}
if(ans!=0)
System.out.println(ans);
else
System.out.println(1);
ans = 1;
a=0;
e=0;
i1=0;
o=0;
u=0;
}
}
}
Iterate over the string and maintain the count of vowels
As soon as you encounter an underscore, multiply count of vowels with the sum.
int sum = 1, noOfVowels = 0;
for(int i=0; i<str.length(); i++) {
if("aeiou".indexOf(str.charAt(i)) >= 0) {
noOfVowels++;
} else if("_".indexOf(str.charAt(i)) >= 0) {
sum = (sum * noOfVowels <= 0) ? 1: sum * noOfVowels;
}
}
return sum;
Input: a_e_i
Output: 2 (aAeAi, aAeEi)
Input: ae_io_
Output: 8
(aeAioA,aeAioE,aeEioA,aeEioE,aeAioI,aeAioO,aeEioI,aeEioO)

How to return a string?

import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();

easier way to find vowels and print them? JAVA

Hey this is my first time posting! I got my program to print out the vowels from an input from user but I feel like I have repeated myself a lot in the for loop. Is there a quicker way to do this? Also is this code readable and in the correct format?
import java.util.Scanner;
public class Task09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String vowels ="";
//input from user
String answer= input.next()
//loop to find vowels
for(int i = 0 ;i<answer.length();i++)
{
char answerPosition = answer.charAt(i);
//checks if there are vowels in code
if (answerPosition =='a'
||answerPosition =='e'
||answerPosition =='i'
||answerPosition =='o'
||answerPosition =='u'
||answerPosition =='A'
||answerPosition =='I'
||answerPosition =='O'
||answerPosition =='U')
{
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}
Try this:
String newString = answer.replaceAll("[^AaeEiIoOuU]", "");
System.out.println(newString);
You wont need for loop as well and your code would be compact and sweet.
You could do:
if ( "aeiouAEIOU".indexOf(answerPosition) >= 0 ) {
vowels += answerPosition + " ";
}
inside the loop.
Additionally, as a matter of style, you might write the iteration slightly differently:
for (char c: answer.toCharArray()) {
if ( "aeiouAEIOU".indexOf(c) >= 0 ) {
vowels += c + " ";
}
}
You can do this way too.
import java.util.Scanner;
public class Hi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String vowels = "";
// input from user
String answer = input.next();
// loop to find vowels
for (int i = 0; i < answer.length(); i++) {
char answerPosition = answer.charAt(i);
char tempAnsPos = Character.toUpperCase(answer.charAt(i));
// checks if there are vowels in code
if (tempAnsPos == 'A' || tempAnsPos == 'E' || tempAnsPos == 'I' || tempAnsPos == 'O' || tempAnsPos == 'U') {
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}

How to manually shuffle letters in a String

I am Writing a game/java program that needs to take a word from a .txt file, then jumble the letters up and ask the user to guess what word it is. I am having two problems:
First is that I receive this error message when I run it:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Proj4.main(Proj4.java:20)
The second problem I am having is jumbling the word. I cannot figure out how to do that without using the shuffle command (which I cannot use).
Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Proj4 {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File ("words.txt"));
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
int lengthList = Integer.parseInt(word[0]);
Scanner s = new Scanner(System.in);
Random randomNumber = new Random();
int i = randomNumber.nextInt(lengthList); //picks a word at random. assigns to "word"
String currentWord = word[i];//picks a word at random. assigns to "currentWord"
int turnScore = 10, finalScore = 0;
char input;
String guess ="a";
do { //do loop for whole program looping
turnScore = 10;
do { //do loop for guessing correct
do{
System.out.println("Current Puzzle: " + currentWord);
System.out.println("Current points for this word: " + turnScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
input = s.nextLine().charAt(0); //assigns input to first letter entered by user
Character.toLowerCase(input); //puts input to lower case
if(input != 'g' && input != 'G' && input != 'h' &&
input != 'H' && input != 'n' && input != 'N' &&
input != 'Q' && input != 'q'){
System.out.println("Invalid Entry. Please input g, n, q or h only! \n ");
}
} while (input != 'g' && input != 'G' && input != 'h' && input != 'H' &&
input != 'n' && input != 'N' && input != 'Q' && input != 'q'); //end do while loop (ask for input)
if (input == 'g') {
System.out.println("Enter Your guess: ");
guess = s.nextLine();
System.out.println("your guess is: " + guess + "\n\nThe word is: " + currentWord);
if (guess.equalsIgnoreCase(currentWord)) {
System.out.println("You Guessed Correct");
System.out.println("Your Score for this word is: " +turnScore );
finalScore = finalScore + turnScore;
}//end if guess = currentWord
else
{
if (turnScore <= 0)
{
turnScore = 0;
}//end if turn score >=0
else
{
turnScore -= 1;
}//end else turn score minus 1.
System.out.println("Nope, Sorry \n\n");
}//end else guess not = to currentWord.
}//end if user input = G.
else if (input == 'n')
{
i = randomNumber.nextInt();
currentWord = word[i];
turnScore = 10;
}//end new word if
else if (input =='h')
{
turnScore = turnScore/2;
Random ranNum = new Random();
int randomLetter = ranNum.nextInt(5);
char hint = currentWord.charAt(randomLetter);
System.out.println("the Letter at spot " + (randomLetter +1) + " is " + hint);
}//end of if input = h
else if (input == 'q')
{
finalScore = finalScore + turnScore;
System.out.println("Goodbye!");
System.out.println("Final Score: " + finalScore);
System.exit(0);
}//end else if for input = Q.
}while (!guess.equalsIgnoreCase(currentWord));
}while (input != 'q');
System.out.println("Your Final Score is: " + finalScore);
System.out.println("Goodbye!");
inFile.close();
}//End main
}//end class
Your exception is caused by these lines of code:
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
//inFile no longer has next, will break when the for loop is entered
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
The easy way to fix this is to redeclare the inFile and read from beginning again.
The best way to fix this is to use a dynamically sized ArrayList:
int counter = 0;
ArrayList<String> word = new ArrayList<String>();
while (inFile.hasNext()) {
word.add(inFile.nextLine());
counter++;
}
This also makes your randomizing much more easy since you can do something sneaky with it.
Here's the documentation on ArrayList.
The key, not the solution, to your second question lies add(int index, E element)
There is a way to shuffle on the fly as you read. You should figure that out, and if you get stuck, then come back.

How to check if a character in a string is a digit or letter

I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.

Categories