Flesch Index program Java - java

I am writing this program that calculates the Flesch index of a passage in Java. A few things: I can't figure out how to make it to where you can input as many words as you like while hitting enter and it will not calculate (something like d tells it that no more input is coming). I am also having trouble with this boolean expression. I have tried & and && and it still doesn't work. I keep getting a message that says, "Syntax error on token "&&", throw expected"
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
// Declare variables for syllables and words
int totalWords = 0;
int totalSyllables = 0;
// Prompt user for a passage of text
System.out.println ("Please enter some text:");
String passage = input.nextLine();
// Words
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == ' ') {
totalWords++;
}
else if (passage.charAt(i) == '.') {
totalWords++;
}
else if (passage.charAt(i) == ':') {
totalWords++;
}
else if (passage.charAt(i) == ';') {
totalWords++;
}
else if (passage.charAt(i) == '?') {
totalWords++;
}
else if (passage.charAt(i) == '!') {
totalWords++;
}
else {
totalWords = totalWords;
}
}
System.out.println ("There are " + totalWords + " words.");
char syllableList [] = {'a', 'e', 'i', 'o', 'u', 'y'};
// Syllables
for (int k = 0; k < syllableList.length; k++)
{
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == syllableList[k]) && (passage.charAt(i) == syllableList[k]); {
totalSyllables = totalSyllables;
}
if (passage.charAt(i) == syllableList[1] + ' ') {
totalSyllables = totalSyllables;
}
if (passage.charAt(i) == syllableList[k]) {
totalSyllables++;
} else {
totalSyllables = totalSyllables;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
}
}
I know I will have to type in the calculations, but right now I was just trying to get it to count the number of words and syllables. Once this works, I will add in the calculation to find the Flesch index. Thanks for the help guys. For some reason I get an error on the line that says
if (passage.charAt(i) == syllableList[k]) && (passage.charAt(i) == syllableList[k]);
And I have no clue why I am getting this or how to fix it.

Related

print the word which has maximum number of vowel in java

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

Java battleship program not printing board correctly

I am having a problem with my java battleship program not printing the coordinates that the user enters. When the user guesses a spot on the board its supposed to update the space with an "X" if its a hit, if not then the board remains the same. But when a user guesses wrong on my program, it prints everything except the space where the user guessed. I believe that my else statement where the board updates is the problem, but any modification I did resulted in the board not printing anything.
import java.util.Random;
import java.util.Scanner;
class Battleship {
public static char randChar(){
final String alphabet = "ABCDE";
final int N = alphabet.length();
char rand;
Random r = new Random();
rand = alphabet.charAt(r.nextInt(N));
return rand;
}
public static void main (String[] args) throws java.lang.Exception {
char[] letters = {' ', 'A', 'B', 'C', 'D', 'E'};
int[] numbers ={1, 2, 3, 4, 5};
int[][] ships = new int[7][2];
char colGuess;
int rowGuess;
Boolean boardFlag=false;
Scanner scan = new Scanner(System.in);
//creates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
System.out.print(letters[j] + "" + numbers[i-1]);
}
System.out.print(" ");
}
System.out.println();
}
//assigns ships to random spots
assignShips(ships);
System.out.println("Enter your guess for the column:");
colGuess = scan.next().charAt(0);
//converts to uppercase
colGuess = Character.toUpperCase(colGuess);
System.out.println("Enter your guess for the row:");
rowGuess = scan.nextInt();
//shows player what they entered
System.out.println("you entered: " + (char) colGuess + rowGuess);
//calls method to check for a hit
fire(colGuess, rowGuess, ships);
boardFlag = fire(colGuess, rowGuess, ships);
System.out.println(boardFlag);
//updates the board
for (int i = 0 ; i <= 5 ; i++) {
for (int j = 0 ; j <= 5 ; j++) {
if (i == 0) {
System.out.print(letters[j] + " ");
}
else if (j == 0) {
System.out.print(numbers[i - 1]);
}
else {
if(letters[j] == colGuess && numbers[i - 1] == rowGuess) {
if(boardFlag==true) {
System.out.print(" " + "X");
}
}
else {
System.out.print(letters[j] + "" + numbers[i - 1]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void assignShips(int[][] ships) {
Random random = new Random();
for(int ship = 0; ship < 7; ship++) {
ships[ship][0] = randChar();
ships[ship][1] = random.nextInt(5);
//gives location of ships, for testing purposes
System.out.print("Ship:" + (ship+1)+ " is located at"+(char)ships[ship][0]+ships[ship][1]+"\n");
}
}
//checks user input to see if we have a hit
public static Boolean fire(char colGuess, int rowGuess, int[][] ships) {
Boolean hitFlag=false;
for(int ship = 0; ship < ships.length; ship++){
if(colGuess ==ships[ship][0] && rowGuess == ships[ship][1]){
hitFlag=true;
}
}
if(hitFlag == true) {
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
}
else {
System.out.println("sorry chief we missed em");
}
return hitFlag;
}
}
The reason its not showing up when you miss is because your net telling it to print anything.
if(letters[j] == colGuess && numbers[i-1] == rowGuess){
if(boardFlag==true) {
System.out.print(" "+"X");
}
}
Your only handling the coordinate the user input if they hit. To fix this you would need an else statement after your if(boardFlag == true)to handle printing if you miss.
The problem is in your update board portion of the code because you don't do anything if the guessed location isn't a hit.
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag) {
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
Full Update Portion:
//updates the board
for (int i = 0 ; i <= 5 ; i++){
for (int j = 0 ; j <= 5 ; j++){
if (i == 0) {
System.out.print(letters[j]+" ");
} else if (j == 0){
System.out.print(numbers[i-1] );
} else {
if(letters[j]==colGuess && numbers[i-1]==rowGuess && boardFlag){
System.out.print(" "+"X");
} else {
System.out.print(letters[j]+""+numbers[i-1]);
}
}
System.out.print(" ");
}
System.out.println();
}
This block (old version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em");
}
Should be (new version):
if(hitFlag==true){
System.out.println("we hit em at "+(char)colGuess+rowGuess+" chief!");
} else {
System.out.println("sorry chief we missed em at " + (char)colGuess+rowGuess);
}
this will print:
sorry chief we missed em at D3 //D3 is a random possible set of coordinates
Rather than:
sorry chief we missed em //Old version
So all you have to add is (char)colGuess+rowGuess, which prints the coordinates of your previous guess.
Comment if you have any questions!

why am I getting run time error:StringIndexOutOfBounds?

Doing my AP Computer Science homework right now but I am stuck with run-time errors. Does anyone know what is wrong with my code?
The program was working fine on Dr.Java but it shows run-time error on my website tester in edhesive...
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<=(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}
Because of ch++ the value of ch is getting incremented after checking this condition (ch++)<=(tweet.length()).
Explanation :
if(tweet.charAt(ch) == '#' && ((ch++)<=(tweet.length())) && (tweet.charAt(ch++)!=' ' && tweet.charAt(ch++)!='\t'))
{
hash++;
}
For above code there are 4 conditions (for i=0):
tweet.charAt(ch) ch = 0
((ch++)<=(tweet.length())) ch = 0, but ch++ so the value will be increamented after the condition check.
(tweet.charAt(ch++) ch=1 (becuase of Point No. 2)
tweet.charAt(ch++) ch = 2 (for the same reason).
Try this:
class Main{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String tweet = scan.nextLine();
int hash = 0;
int attr = 0;
int link = 0;
int ch = 0;
if(tweet.length()>140)
{
System.out.println("Excess Characters: " + (tweet.length() - 140 ));
}
else
{
tweet=tweet.toLowerCase();
System.out.println("Length Correct");
for(ch=0; ch<tweet.length(); ch++)
{
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
hash++;
}
if(tweet.charAt(ch) == '#' && ((ch+1)<(tweet.length())) && (tweet.charAt(ch+1)!=' ' && tweet.charAt(ch+1)!='\t'))
{
attr++;
}
if(tweet.charAt(ch) == 'h' && ((ch + 7)<(tweet.length())))
{
String a = new String("http://");
String sub = new String(tweet.substring(ch, ch + 7));
if (sub.equals(a))
{link++;}
}
}
System.out.println("Number of Hashtags: " + hash);
System.out.println("Number of Attributions: " + attr);
System.out.println("Number of Links: " + link);
}
}
}

Java Why do I get this error? Exception in thread "main" java.lang.NullPointerException

This is the code that it is giving me the error for on the line with >>>>>>> I've already looked at this thread Exceptions but I still do not understand what I need to change :( I am a total beginner to programming.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class manyVowels {
public static final String wordList = "words.txt";
public static void main(String[] args) {
Scanner fileIn = null;
try {
//locate and open file
fileIn = new Scanner(new FileInputStream("words.txt"));
} catch (FileNotFoundException e) {
//if the file cannot be found, the program prints the message and quits
System.out.println("File not found. ");
System.exit(0);
}
String word = null;
if (fileIn.hasNext()) //if there is another word continue
{
String finalWord = null; // defines the word with most consecutive vowels
int maxVowels = 0;//sets initial value to 0
while (fileIn.hasNext()) {
// for each word in the file
int vowels = 0;
/*error here-->*/ for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxVowels
if (hasVowels(word.charAt(i))) {
// consonants reset this to 0
vowels++;
} else {
// reached the end of the word so check if the count is higher than maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
vowels = 0;
}
}
// comparing vowels to maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
}
//seek vowels
word = fileIn.next();
for (int i = 0; i < word.length(); i++) {
if
((word.charAt(i) == 'A')
|| (word.charAt(i) == 'E')
|| (word.charAt(i) == 'I')
|| (word.charAt(i) == 'O')
|| (word.charAt(i) == 'U')
|| (word.charAt(i) == 'a')
|| (word.charAt(i) == 'e')
|| (word.charAt(i) == 'i')
|| (word.charAt(i) == 'o')
|| (word.charAt(i) == 'u')) {
//prints the final word with the most consecutive vowels
System.out.println("The word with the most consecutive vowels is: " + word);
System.exit(0);
}
}
}
}
private static boolean hasVowels(char charAt) {
throw new UnsupportedOperationException("Inserted by template."); //NetBeans generated method
}
}
Following the logic, you initialize the String word to null, and then proceed to call word.length().
word, being null, has no length(). Thus, the NullPointerException.
Assign a string to word before attempting to measure its length.
String word = "Hello!";
The variable word seems to be null, I think you skipped an instruction in which you fill it with a word read from fileIn. Your code should read something like this:
while (fileIn.hasNext()) {
// for each word in the file
word = fileIn.next();
int vowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
...
you defined word as a null. When you say word.length() it means you are saying
null.length() that's why you are getting null pointer exception.
You should initialize String variable "word" before doing any operation( calling any string method by using '.' )
If you have any predefined value, initialize with that else initialize with empty string.
String word = "xyz" ;
String word = "" ;

Not sure how to approach english into latin pig java code

Here's my attempt to write this code but I'm getting lost with a main part.I'm not sure how the loop will know when a new word starts.For now I know only loops and if-else statements.I would really appreciate if you could just push me in a right direction because this problem is way too hard for me.
Rules of pig latin:
1)If a word begins with a vowel,add a dash and "way" to the end.
2)Otherwise,add a dash,move the first letter to the end,and add "ay"
/*Enter a line of text: This is a test.
Input: this is a test.
Output: his-tay is-way a-way est-tay.
*/
import java.util.Scanner;
public class PigLatin
{
public static void main(String[]args)
{
int count;
String input;
char empty = ' ',first;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
System.out.println();
for(count = 0; count < input.length(); count++)
if(input.charAt(0) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(count + 1) + "-" + input.charAt(0) + "ay");
else if(input.charAt(count) == empty)
first = input.charAt(count + 1)
if(input.charAt(first) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(first + 1) + "-" + input.charAt(first) + "ay");
else if()
System.out.print("-way"); //I'm lost here.
}
}
Try the following:
import java.util.Scanner;
public class PigLatin {
static final char vowelRegex = "^[aeiouy]"; //Is y a vowel?
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String input = keyboard.nextLine();
String[] words = input.split(' ');
for(int i=0; i<words.length; i++) {
if(words[i].matches(vowelRegex)) {
System.out.print(words[i] + "-way ");
} else {
System.out.println(words[i].substring(1) + words[i].charAt(0) + "-ay ";
}
}
}
}

Categories