I'm writing a program about musical chords. I want the user to input A-G or a-g, but it can also be # or - (flat), and also m (minor).
It's running, but if you put in a#m, you get
Enter a musical piano chord name:
A
I need it to keep reading the if statements so that if the input is 3 characters, I can delineate what that char should be.
I haven't added the section on sharps and flats yet.
import java.util.Scanner;
public class Hwk9 {
public static void main(String[] args) {
String chord;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a musical piano chord name: ");
chord = stdin.nextLine();
String finalChord = validChord(chord);
System.out.println(finalChord);
}
public static String validChord(String input) {
if (input.length() > 3 && input.length() < 1) {
input = "Invalid chord";
}
char note = input.charAt(0);
char capNote = chordCapitalize(note);
if (capNote == 'A') {
input = capNote + "";
}
else if (capNote == 'B') {
input = capNote + "";
}
else if (capNote == 'C') {
input = capNote + "";
}
else if (capNote == 'D') {
input = capNote + "";
}
else if (capNote == 'E') {
input = capNote + "";
}
else if (capNote == 'F') {
input = capNote + "";
}
else if (capNote == 'G') {
input = capNote + "";
}
else {
input = "Invalid chord";
}
if (input.length() == 3) { *<<<<<<This section is not going through*
char minor = input.charAt(2);
if (minor == 'm') {
input = capNote + "" + minor;
}
else {
input = "Invalid chord";
}
}
return input;
}
public static char chordCapitalize(char input) {
String note = input + "";
String caps = note.toUpperCase();
char capNote = caps.charAt(0);
return capNote;
}
}
The problem is you are assigning the capitalized chord back to input in the if blocks. You need to have a local variable for that and not re-assign it to input
If you assign input the value of capNote, length of input will always be one.
String result;
if (capNote == 'A') {
result = capNote + "";
}
else if (capNote == 'B') {
result = capNote + "";
}
//Rest of code
if (input.length() == 3) {
char minor = input.charAt(2);
if (minor == 'm') {
result = capNote + "" + minor;
}
else {
result = "Invalid chord";
}
}
return result;
Related
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
I am trying to make a fraction calculator that quits when you type quit regardless of the casing. However these two errors have been coming up. Any suggestion?? Thanks a lot.
FractionCalculator.java:70: error: '(' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: ')' expected
else if kb.next().equalsIgnoreCase("quit"){
^
FractionCalculator.java:70: error: 'else' without 'if'
else if kb.next().equalsIgnoreCase("quit"){
^
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner (System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " +userName +", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner (System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: " +input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
}
else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*' || input.charAt(i) == '/' && operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i=i+1;
}
if (input.charAt(i) != ' ' && value1Done == true && value2Done == false) {
value2Str += input.charAt(i);
}
else {
value2Done = false;
}
else if kb.next().equalsIgnoreCase("quit"){
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
//correctFormat = true;
}
}
System.out.println("value1Str is: " +value1Str);
System.out.println("Operator is: " +operator);
System.out.println("Value2Str is: " +value2Str);
}
}
You have errors in using if condition .
Updating your code with proper use of if , if else conditions.
import java.util.*;
public class FractionCalculator {
// useDelimiter or split method in string class
public static void main(String[] args) {
Greeting();
produceAnswer();
}
static String value1Str = "";
static String value2Str = "";
static char operator = ' ';
public static void Greeting() {
Scanner kb = new Scanner(System.in);
String userName;
System.out.print("Hello Person, What is your first name: ");
userName = kb.next();
System.out.println("Hi " + userName
+ ", welcome to the great mystical fraction calculator.");
}
public static void produceAnswer() {
Scanner kb = new Scanner(System.in);
System.out.println("What is your input or type quit to leave?");
String input = kb.nextLine();
boolean value1Done = false;
boolean operatorDone = false;
boolean value2Done = false;
boolean correctFormat = false;
for (int i = 0; i < input.length(); i++) {
System.out.println("The input of given string is: "
+ input.charAt(i));
if (input.charAt(i) != ' ' && value1Done == false) {
value1Str += input.charAt(i);
} else {
value1Done = true;
}
if (input.charAt(i) == '+' || input.charAt(i) == '-'
|| input.charAt(i) == '*' || input.charAt(i) == '/'
&& operatorDone == false && value1Done == true) {
operator = input.charAt(i);
operatorDone = true;
i = i + 1;
}
if (input.charAt(i) != ' ' && value1Done == true
&& value2Done == false) {
value2Str += input.charAt(i);
} else if (kb.next().equalsIgnoreCase("quit")) {
System.out.println("Why are you leaving? Comeback soon bby");
break;
// quit = true;
// correctFormat = true;
} else {
value2Done = false;
}
}
System.out.println("value1Str is: " + value1Str);
System.out.println("Operator is: " + operator);
System.out.println("Value2Str is: " + value2Str);
}
}
Check how to use if-then and if-then-else Statements at this link :
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
You have a malformed if statement:
if (...) { ....
}
else {
value2Done = false;
}
else // ERROR
An if statement cannot have two else clauses ... which you have here.
Indeed, the 3rd error message is saying that explicitly.
I am writing a program that is supposed to calculate the Flesch index of a passage or string and tell the minimum education level required to comprehend.
What is supposed to happen is a person types in a string that the want to be calculated and the program is supposed to count the number of words and count the number of sentences as well as go through each word and calculate how many syllables there are in the word and add that to the total syllable counter. The way to calculate syllables is to count the number of adjacent vowels in a word, so "Computer" for instance has the vowels o, u, and e so 3 syllables. But, if the word ends in the letter e, subtract 1 from the total syllable count so, "Passage" has a, a, and e, but since the e is at the end, the syllable count is 2.
Here is what I got so far:
// Import scanner to get input from the user
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
public static final double BASE = 206.835;
public static final double WORD_LENGTH_PENALTY = 84.6;
public static final double SENTENCE_LENGTH_PENALTY = 1.015;
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++;
}
}
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]) {
totalSyllables = totalSyllables + 1;
}
if (lastChar(passage) == 'E' || lastChar(passage) == 'e') {
totalSyllables = totalSyllables - 1;
} else {
break;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
input.close();
public static char lastChar (String aWord)
{
char aChar = aWord.charAt(aWord.length() - 2);
System.out.print (aChar);
return aChar;
}
/** Return true if the last character in the parameter word is
* a period, question mark, or exclaimation point, and false
* otherwise
**/
public static boolean sentenceEnd (String word)
{
if (lastChar(passage) == '.') {
return true;
} else if (lastChar(passage) == '?') {
return true;
} else if (lastChar(passage) == '!') {
return true;
} else {
return false;
}
}
double fleschIndex = BASE - WORD_LENGTH_PENALTY * (totalSyllables / totalWords) - SENTENCE_LENGTH_PENALTY * (totalWords / totalSentences);
if (fleschIndex > 100) {
educationLevel = "4th grader";
} else if (fleschIndex <= 100) {
educationLevel = "5th grader";
} else if (fleschIndex <= 90) {
educationLevel = "6th grader";
} else if (fleschIndex <= 80) {
educationLevel = "7th grader";
} else if (fleschIndex <= 70) {
educationLevel = "8th grader";
} else if (fleschIndex <= 60) {
educationLevel = "9th grader";
} else if (fleschIndex <= 50) {
educationLevel = "high school graduate";
} else if (fleschIndex <= 30) {
educationLevel = "college graduate";
} else if (fleschIndex < 0) {
educationLevel = "law school graduate";
}
System.out.println ("The Flesch idex is " + fleschIndex + ".");
System.out.println ("The text can be understood by a " + educationLevel + ".");
}
}
I keep getting some weird error messages telling me to put semi-colons around the boolean declarations which makes no sense to me.
It looks to me like you mixed up your methods.
The methods sentenceEnd and lastChar are inside the main-method. This is not allowed.
They have to be outside of the main-method but inside the Flesch-Class.
Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.
I need to convert hexadecimal to decimal using different methods. When I enter numbers that are correct hexadecimal numbers, my program displays the decimal value and says that the number is valid. However, when I enter incorrect hexadecimal values, my program crashes.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
switch(choice){
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
if (isValid) {
System.out.println(hex + " is valid");
}
break;
case 'n':
System.out.print("Quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
public static long convert (String hexValue) {
long decimal = 0;
boolean isNegative = false;
int a = 0;
if (hexValue.charAt(0) == '-') {
isNegative = true;
a = 1;
}
for (int i = a; i<hexValue.length(); i++) {
decimal = decimal*16;
if (hexValue.charAt(i) >= '0' && hexValue.charAt(i) <= '9') {
decimal += hexValue.charAt(i) - '0';
}
else if (hexValue.charAt(i) >= 'a' && hexValue.charAt(i) <= 'f') {
decimal += hexValue.charAt(i) - 'a' + 10;
}
}
if (isNegative == true) {
decimal *= -1;
}
return decimal;
}
}
why is it crashing and how can I fix it so that it displays "invalid" when incorrect hexadecimal digits are entered?
If you enter an invalid hex number, Integer.parseInt() will throw NumberFormatException. Change your code like this:
...
isValid = valid(hex);
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
...
do {
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
int base = 10;
switch(choice)
{
case 'y':
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase(); //I'm not sure if this step is necessary
try {
Integer value = Integer.parseInt(hex, 16);
System.out.println("Valid hex format");
System.out.println("Hex: " + hex);
System.out.println("Decimal: " + value);
}
catch (NumberFormatException e) {
System.out.println("Invalid hex format");
System.out.println("Input: " + hex);
}
break;
case 'n':
System.out.print("Quit");
break
}
} while (choice != 'n');
Now you can delete all your helper methods
Add Integer value = Integer.parseInt(hex,16); inside if statement and print invalid in else block.
if (isValid) {
Integer value = Integer.parseInt(hex,16);
System.out.println("The value: " + value);
System.out.println(hex + " is valid");
}
else{
System.out.println("invalid");
}
Updated:
Change your valid method as follows:
public static boolean valid(String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i = a; i < validString.length(); i++) {
// if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F') || (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) {
// return false;
// }
char ch=validString.charAt(i);
if(!(Character.isDigit(ch) || (Character.isLetter(ch) && ((ch-'A')<=5))) ){
return false;
}
}
return true;
}