How to count certain characters in a text file using loops - java

I need help on a project that counts all of the vowels in the Ulysses text, by James Joyce. I am not sure how to make the program read the text file that I have inserted in the root folder of the project. I'm also not sure how to make a loop that will count all of the vowels. This is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Vowel counts in Ulysses by James Joyce:");
int a = 0;
int e = 0;
int i = 0;
int o = 0;
int u = 0;
System.out.println("a = " + a);
System.out.println("e = " + e);
System.out.println("i = " + i);
System.out.println("o = " + o);
System.out.println("u = " + u);
FileReader reader = new FileReader("ulysses.txt");
Scanner input = new Scanner(reader);
while (input.hasNextLine()) {
String line = input.nextLine();
}
}}
The output should look something like this (with all the numbers right justified):
Vowel counts in Ulysses by James Joyce:
a = 94126
e = 143276
i = 82512
o = 92743
u = 33786

I had to do this once, and I think it was something similar to this.
while (input.hasNextLine()) {
String line = input.nextLine();
//toUpperCase() normalizes all the letters so you don't have to count upper and lower
line.toUpperCase();
char[] c = line.toCharArray();
for (int j = 0; j < c.length(); j++)
switch(c[i])
{
case "A";
a++;
case "E";
e++;
case "I";
i++;
case "O";
o++;
case "U";
u++;
}
}

import java.util.Scanner;
public class Smashcode {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("samplefile.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Create the Content String
String fileContent = "";
// Read data from a file
while (input.hasNext()) {
fileContent += input.next() + " ";
}
// Close the file
input.close();
//Split the string into a character array
char[] charArr = fileContent.toCharArray();
//loop through every character to find the vowels
int counter = 0;
for(char c : charArr)
{
if(c == 'a')
counter_a++;
if(c == 'e')
counter_b++;
if(c == 'i')
counter_i++;
if(c == 'o')
counter_o++;
if(c == 'u')
counter_u++;
}
//number of vowels
System.out.println("Number of Vowels: " + (counter_a+counter_e+counter_o+counter_i+counter_u));
System.out.println(counter_a);
System.out.println(counter_e);
System.out.println(counter_i);
System.out.println(counter_o);
System.out.println(counter_u);
}}
Hope you like my work.Happy coding

Related

How to get correct output for Pig Latin translator using JAVA

I am coding a JAVA application that translates english to pig latin. My application runs with no actual errors but the output is automatic and incorrect. This application will continue to run if the user selects "y".
Can you all see where my error lies?
Thank you.
CODE:
import java.util.Scanner;
public class PigLatin2 {
public static void main(String[] args) {
// create a Scanner object
Scanner sc = new Scanner(System.in);
// Run through the loop of calculations while user choice is equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("Enter a line to be translated");
System.out.println();
//Get String entered
String userInput = sc.toString();
//Line break
System.out.println();
String[] words = userInput.split(" ");
String output = "";
for(int i = 0; i < words.length; i++) {
String pigLatin = translated(words[i]);
output += pigLatin + " ";
}
System.out.println(output);
//Scan next line
sc.nextLine();
//line break
System.out.println();
// Ask use they want to continue
System.out.print("Continue? (y/n): ");
//Users choice
choice = sc.nextLine();
System.out.println();
}//END WHILE LOOP
//Close scanner object
sc.close();
}//END MAIN METHOD
private static String translated(String words) {
String lowerCase = words.toLowerCase();
int firstVowel = -1;
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCase.length(); i++) {
ch = lowerCase.charAt(i);
if (startsWithVowel(ch)) {
firstVowel = i;
break;
}
}
if (firstVowel == 0) {
return lowerCase + "way";
}else {
String one = lowerCase.substring(firstVowel);
String two = lowerCase.substring(0, firstVowel);
return one + two + "ay";
}
}
public static Boolean startsWithVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
This is the output I get automatically:
ava.util.scanner[delimiters=\p{javawhitespace}+][position=0][matchjay alid=false][needvay input=false][sourceway osed=false][skipped=false][groupclay eparator=\,][decimalsay eparator=.][positivesay efix=][negativepray efix=\q-\e][positivepray uffix=][negativesay uffix=][nansay ing=\qnan\e][infinitystray ing=\q?\e]stray

Counting vowels in a string and wrong output?

I am very new to java and I was wondering if you could help me out. Here is my code:
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
for (int i = 0; i <= length; i++) {
String letter = string.substring(i, ++i);
if (letter.equalsIgnoreCase("a")){vowels++;}
if (letter.equalsIgnoreCase("e")){vowels++;}
if (letter.equalsIgnoreCase("i")){vowels++;}
if (letter.equalsIgnoreCase("o")){vowels++;}
if (letter.equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
The number is off but I can't figure out why.
This here is wrong
string.substring(i, ++i)
because the variable i is already incremented in the for-loop
so you are basically skipping chars in the string
implement the right logic, use the right data type
int length = string.length();
for (int i = 0; i < length; i++) {
char letter = string.charAt(i);
System.out.println(letter);
if (letter == 'a') {
vowels++;
} else if (letter == 'e') {
vowels++;
} else if (letter == 'i') {
vowels++;
} else if (letter == 'o') {
vowels++;
} else if (letter == 'u') {
vowels++;
}
}
Here is another solution you could try:
The split method will split the string into a String array. Then in your for loop it will check every item in your array.
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
String[] stringArray = string.split("");
for (int i = 0; i < length; i++) { //I took out the = sign in your for loop arguments.
if (stringArray[i].equalsIgnoreCase("a")){vowels++;}
if (stringArray[i].equalsIgnoreCase("e")){vowels++;}
if (stringArray[i].equalsIgnoreCase("i")){vowels++;}
if (stringArray[i].equalsIgnoreCase("o")){vowels++;}
if (stringArray[i].equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}

Guess the word game in Java

i have a problem writing guess the word game java code .
i'll show you my current code and till you the problem .
import java.util.Scanner;
class Q
{
public static void main(String argss[])
{
String strs[] = { "kareem", "java", "izz", "tamtam", "anas" };
Scanner input = new Scanner(System.in);
int index = ((int) (Math.random() * 5));
int points = 50;
String c;
boolean result = false;
boolean finalResult = false;
boolean tempResult = false;
String word = strs[index];
System.out.println(
"\t *** Enter a character and guess the world*** \n\t ***You will loose if your points become 0 *** \n ");
System.out.println(stars(word));
System.out.println("Your points: " + points);
System.out.print("Enter and guess a character! ");
String temp = stars(word);
String oldTemp = temp;
c = input.next();
while (points > 0)
{
for (int i = 0; i < word.length(); i++)
{
result = (word.charAt(i) + "").equals(c);
if (result == true)
{
temp = toChar(i, temp, c);
}
}
finalResult = temp.equals(word);
tempResult = temp.equals(oldTemp);
System.out.println(temp);
if (finalResult == true)
{
System.out.println("\n \n YOU HAVE GUESSED THE WORLD,YOU WON ! ");
break;
}
if (tempResult == true)
{
points = points - 5;
System.out.println("False and now your points are " + points);
}
else if (tempResult == false)
{
System.out.println("True and now your points are " + points);
}
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
System.out.print("Guess another time,enter a character: ");
c = input.next();
}
}
public static String stars(String word)
{
String temp = "";
for (int i = 0; i < word.length(); i++)
temp = temp + "*";
return temp;
}
public static String toChar(int index, String temp, String c)
{
char[] tempChar = temp.toCharArray();
char s = c.charAt(0);
tempChar[index] = s;
temp = String.valueOf(tempChar);
return temp;
}
}
now as you can see in line number 39 , i have a little problem here because when its false it'll be no longer right .
do you know another way to compare if the entry is right or not ?
Doesn't look like you are changing oldTemp inside the while loop. Try setting it to equal to temp after all of the if statements.
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
oldTemp = temp; // add this here
System.out.print("Guess another time,enter a character: ");
c = input.next();

Java: Searching a 2D array for Strings and displaying the data

I am creating a program which acts as a translator for given words. I have created a text file with the data I am using, reading that into a 2D array (English in column 0, translation in column 1, 16 rows in total). I prompt the user to enter a string and pass that string, the 2D, and a blank String to hold the translation to my translation method (named: turnKlingon). I am using the String tokenizer to pick out specific words. My problem is that I cannot figure out how to search my 2D array in column 0 for the English and only print the column 1 translated word.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
System.out.println("Klingon Translator");
System.out.println();
System.out.println();
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
String Klingon = " ";
turnKlingon(Klingon, userString, translate);
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated to Klingon: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String Klingon, String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println("Number of Tokens: "+ numberOfWords);
int counter = 1;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
System.out.print(s2 + "_"); //string tokenizer
for(int r = 0; r < translate.length; r++)
{
for(int c = 0; c < translate[r].length; c++)
{
if (translate[r][c].compareTo(s2) == 0)
{
translate[0] = translate[1];
}
}
System.out.println(translate[0] + "," + translate[1]);
counter++; //string tokenizer
}//end while
}
}
}
After messing around with this code for a few hours I finally managed to solve my own problem. I also added a while true loop in the main method to allow the user to translating multiple times as well as an option to translate to another language (German) though I have omitted that method from this reply.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
Scanner input = new Scanner(System.in);
System.out.println("English to Klingon/German Translator");
System.out.println();
System.out.println();
while (true)
{
int again = 999;
int language = 999;
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
System.out.println("Would you like to translate to Klingon or German? \n Press 1 for Klingon: \n Press 2 for German: ");
language = input.nextInt();
if (language == 1)
{
turnKlingon(userString, translate);
}
else if (language == 2)
{
turnGerman(userString, translate);
}
else
{
System.out.println("Invalid input");
}
System.out.println();
System.out.println();
System.out.println("Would you like to translate another sentence? \n Press 1 for yes or 0 for no: ");
again = input.nextInt();
if (again == 0)
{
System.out.println("Goodbye!");
break;
}
else if (again == 1)
{
continue;
}
}
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println();
System.out.println("Any words that cannot be directly \n translated will remain in English");
System.out.println("____________________________________");
System.out.println();
System.out.print("Translation: ");
int counter = 1;
boolean found = false;
int translateCounter = 0;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
//string tokenizer
for(int r = 0; r < 16; r++)
{
for(int c = 0; c < 18; c++)
{
found = false;
if (translateCounter == 16)
{
System.out.print(s2+ " ");
translateCounter = 0;
break;
}
else if (translate[r][0].compareTo(s2) == 0)
{
found = true;
}
else if (translate[r][0].compareTo(s2) != 0)
{
found = false;
r++;
c = -1;;
translateCounter++;
continue;
}
if (found == true)
{
System.out.print(translate[r][1]+ " ");
translateCounter = 0;
c = -1;
r = -1;
break;
}
}
counter++;//string tokenizer
break;
}//end while
}
}

Repetition Structures, Procedure Method

public static void main (String args[])
{
String c = "Message";
int width;
int height;
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println("Enter your width: ");
width=sc.nextInt();
System.out.println("Enter your height: ");
height=sc.nextInt();
System.out.println();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height-1) {
System.out.print(character);
} else if (j ==width-1) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
}
I am trying to make the MESSAGE display in the rectangle. Also, is there a way i can move my rectangle in the center of the screen too?
That code will do your trick but please notice that this is ugly.
First you are taking the whole user input line instead of the first character.
public static void main(String args[]) {
String c = "Message";
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 13; j++) {
if (i == 0 || i == 2) {
System.out.print(character);
} else if (j == 0) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
output :
aaaaaaaaaaaaa
a Message a
aaaaaaaaaaaaa
Don't use the [for loop], the StringUtils class in Apache Commons Lang3 can help you make repeating String.
See:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html
there are 3 methods:
(1)static String repeat(char ch, int repeat)
Returns padding using the specified delimiter repeated to a given length.
(2)static String repeat(String str, int repeat)
Repeat a String repeat times to form a new String.
(3)static String repeat(String str, String separator, int repeat)
Repeat a String repeat times to form a new String, with a String separator injected each time.

Categories

Resources