I've been following Tony Gaddis's programming challenges in his book and I've tried doing the "vowels and consonants program". The program will ask the user to input any string, and then it will count the number of vowels or consonants within that string. I was able to code most of it but there has been a problem with the output. Hope you guys can help me with this one.
The problem is like this:
************************|
1 - Count Vowels
2 - Count Consonants
3 - Exit
Enter mode:1
****VOWELS****
Enter words:abracadabra
NUMBER OF VOWELS: 5
Do you want to input again(y/n):n
************************|
1 - Count Vowels
2 - Count Consonants
3 - Exit
Enter mode:1
(and then it'll just end here)
First, I chose mode 1 for counting vowels and then if typed in any string. Then, it did successfully count the number of vowels and it will ask me if i want to input again, I've typed in n for no. The code went back to choosing modes and then, I enter 1 again to count for vowels. This time, it did nothing. It just stopped, where supposedly I should enter a string again and etc. The same thing happens also when I choose 2 for counting consonants.
Here is my code:
PART 1:
package Test;
public class VowelMain {
private String words;
private int vowel = 0;
public VowelMain(String w){
words = w;
setVowel(words);
}
public void setVowel(String words){
char[]chunks = words.toCharArray();
for(int x = 0;x < chunks.length;x++){
if(chunks[x]=='a' || chunks[x]=='e' || chunks[x]=='i' || chunks[x]=='o' || chunks[x]=='u'){
vowel += 1;
}
}
}
public int getVowel(){
return vowel;
}
}
PART II:
package Test;
public class ConsonantMain {
private String words;
private int consonant = 0;
public ConsonantMain(String w){
words = w;
setConsonant(words);
}
public void setConsonant(String words){
char[]chunks = words.toCharArray();
for(int x = 0;x < chunks.length;x++){
if(chunks[x]=='a' || chunks[x]=='e' || chunks[x]=='i' || chunks[x]=='o' || chunks[x]=='u'){
}else{
consonant += 1;
}
}
}
public int getConsonant(){
return consonant;
}
}
PART III:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args){
int mode = getMode();
operation(mode);
}
public static void operation(int mode){
Scanner hold = new Scanner(System.in);
String words;
String response;
while(mode == 1 || mode == 2 || mode == 3){
switch(mode){
case 1:
System.out.print("****VOWELS****\n");
do{
System.out.print("Enter words:");
words = hold.nextLine();
VowelMain t = new VowelMain(words);
System.out.println("NUMBER OF VOWELS: " + t.getVowel());
System.out.print("Do you want to input again(y/n):");
response = hold.nextLine();
if(response.equalsIgnoreCase("n")){
mode = -1;
getMode();
}
}while(response.equalsIgnoreCase("y"));
break;
case 2:
System.out.print("****CONSONANTS****\n");
do{
System.out.print("Enter words:");
words = hold.nextLine();
ConsonantMain c = new ConsonantMain(words);
System.out.println("NUMBER OF CONSONANTS: " + c.getConsonant());
System.out.print("Do you want to input again(y/n):");
response = hold.nextLine();
if(response.equalsIgnoreCase("n")){
mode = -1;
getMode();
}
}while(response.equalsIgnoreCase("y"));
break;
case 3:
System.exit(0);
break;
default:
System.out.println("ERROR!");
break;
}
}
}
public static int getMode(){
Scanner hold = new Scanner(System.in);
int mode;
System.out.println("************************");
System.out.println("1 - Count Vowels");
System.out.println("2 - Count Consonants");
System.out.println("3 - Exit");
System.out.print("Enter mode:");
mode = hold.nextInt();
return mode;
}
}
Each time you put
mode = -1;
getMode();
You should replace it with:
mode = getMode();
Here's why. As RealSkeptic said, getMode() is returning a temporary mode value, not the mode value being used in your loop. By assigning the loop mode to the temporary mode (through the return statement) your code will work fine.
Your function is terminating after a loop when we input "n" and invokes the getMode function which is needed here after the user inputs "n".
All you have to do is remove the line getMode() from your if statement in your case 2: and case 3: as shown below:
if(response.equalsIgnoreCase("n")){
mode = -1;
getMode();
}
and change it to,
if(response.equalsIgnoreCase("n")){
mode = getMode();
}
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
What this programme does is;
Prompts for number of testcases,
User then inputs lines of strings which are the test case.
Program is to count the number of vowels in each test case.
then print out the each test case.
btw for this particular program "y" is also a vowel
For instance;
Number of test:
4
githsajklu
bsa uiqsacva
o h qi samsauq sajahhsa
skajayyosak
answer:
5 4 13 2
The problem is that the program doesnt read the last line/input. it just brings the count for the first 3 inputs but not the last. I hope I am clear enough
import java.util.Scanner;
/*
* Counts number of Vowels in each line
*/
public class VowelCount {
/*
*
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
//prompt user for number of test case
System.out.println("Type in number of Test Cases");
int testcases = input.nextInt();
String[] line = new String[testcases];
String newline;
for(int i=0; i<testcases; i++)
{
//initialize input to line 1,2,3 e.t.c
line[i] = input2.nextLine();
//remove all white spaces
newline =line[i].replaceAll(" ", "");
display(testcases, newline);
}
}
/*
* counts how many vowels are in eace line of input
*/
public static int Counter(String input)
{
//start count from 0;
int counter = 0;
for(int i = 0; i<input.length(); i++)
{
//set character at position i to Dstr
char dStr = input.charAt(i);
//compare if dstr is a vowel
if(dStr == 'i' || dStr == 'u' || dStr == 'o' || dStr == 'a' || dStr == 'e' || dStr == 'y')
{
//increase when characte is a vowel
counter++;
}
}
//return the last count
return counter;
}
/*
* diplay the total count;
*/
public static void display(int testcases, String input)
{
System.out.print(" "+Counter(input));
}
}
Do a scan.nextLine() after you read the amount of test cases. Don't know why it works like that, someone feel free to explain, but if you're reading a an int, then a string, you can either do
int n = Integer.parseInt(scan.nextLine());
or
int n = scan.nextInt();
scan.nextLine();
Also, I know you didn't ask, but here's a much simpler way to count the amount of vowels.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
for(int i = 0; i < n; i++){
String str = scan.nextLine();
System.out.println(str.replaceAll("[^AEIOUaeiouYy]", "").length());
}
}
What that does is erase everything that is not a vowel (and y), and prints the length of it. Really not sure if it's faster, but it's a lot simpler.
Actually, here I'm testing and it is working just fine, it is getting exactly how many inputs I asked for.
My console:
Type in number of Test Cases
4
werty
2
sdfghj
0
xdcfvgh
0
xsdfgh
0
Sometimes, having less code can make things clearer:
void printVowelCount(String text) {
System.out.println(text.replaceAll("[^aeiouAEIOU]", "").length());
}
I have wrote this code and now i'm practicing and i'm trying it to write it in a different or more efficient way. Basically this code asks the user to enter a word and the second player guesses the letters of the word with 6 tries and at the end there is one last chance to guess the whole entire word. Any suggestions on how i can write this code in a simple way?
static int NUM_OF_TRIES = 6;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
boolean a = true;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(0) == word.charAt(j)) {
System.out.println(" at position " + (j + 1));
a = false;
break;
}
}
if (a) {
System.out.println("Sorry not letter " + guess.charAt(0));
continue;
}
}
System.out.println("Enter your last guess: ");
String wordComp;
wordComp = keyboard.next();
if (wordComp.equals(word)) {
System.out.println("You got it!");
} else {
System.out.println("Sorry you lost!");
}
}
}
Well, here is a shorter version:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
int index = word.indexOf(guess.charAt(0));
if (index == -1)
System.out.println("Sorry not letter " + guess.charAt(0));
else
System.out.println(" at position " + (index + 1));
}
System.out.println("Enter your last guess: ");
String wordComp = keyboard.next();
if (wordComp.equals(word))
System.out.println("You got it!");
else
System.out.println("Sorry you lost!");
}
---First of all you'll have to ensure that
word.length <=guess.length
or you'll run into an exception.--- edit: that was obv not correct
Can't test right now bc I'm on my mobile, but as far as I can see, you'll run into problems if the word to guess has the same letter multiple times, since you're breaking out of the loop after finding the equal first letter.
As mentioned in comments, the comparison could be done by a method like
private static List<Integer> getLetterIndices(String word, char letter);
Then you won't need your boolean to indicate correct guesses, but a list of indices found
And of course you can do an object oriented approach instead of the static main method (not that it's faster to implement or better performance, just for practicing), perhaps something in the lines of this:
public class WordToGuess{
private Map<Character,List<Integer>> letter2indices;//...
public WordToGuess(String word){
parseIndices(word);
}
//parse indices of each letter to the map
private void parseIndices(String word);
public List<Integer> getLetterIndices(char letter);
}
I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}
I'm having trouble with an assignment that I'm working on. Here is the prompt:
Create a DigitExtractor application that prompts the user for an integer (in the range: 0-999) and then displays either the ones, tens, or hundreds digit of the number. The user will select from a menu which digit they wish to display.
This program needs to be written as a class. The menu will be your driver program that you submit with the class so your instructor can use it to test the class.
Here is my code for it:
import java.io.*;
import java.util.*;
public class TestingMenu
{
public int number;
public int units;
public int tens;
public int hundreds;
public TestingMenu(int input)
{
number = input;
units = number%10;
tens = number%10;
hundreds = number%10;
}
public int return_units()
{
return units;
}
public int return_tens()
{
return tens;
}
public int return_hundreds()
{
return hundreds;
}
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
TestingMenu num;
int choice;
int input;
do
{
System.out.print("Enter a number(0-999): ");
input = kbReader.nextInt();
System.out.println("");
System.out.println("Options");
System.out.println("1) Units");
System.out.println("2) Tens");
System.out.println("3) Hundreds");
System.out.println("4) Quit");
num = new TestingMenu(input);
System.out.print("Enter your choice: ");
choice = kbReader.nextInt();
switch(choice)
{
case 1:
System.out.println("The units digit is: " + num.return_units());
break;
case 2:
System.out.println("The tens digit is: " + num.return_tens());
break;
case 3: System.out.println("The hundreds digit is: " + num.return_hundreds());
break;
case 4:
System.exit(4);
break;
default:
System.out.print("Invalid. Select a number from the given options.");
choice = kbReader.nextInt();
}
}
while(choice != 4);
}
}
I think I've almost got it, but I'm having issues whenever I test it. When I input a number such as 987 and I run all the options from 1-3, I keep getting 7 for the ones, tens, and hundreds. 4 exits the program and works okay, but I've tested this numerous times. Overall, it seems to only print the last digit.
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 1
The units digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 2
The tens digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 3
The hundreds digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 4
Could someone help me identify the error? I don't really know what went wrong with this program despite working on it for a few hours. Thanks in advance. All the help and feedback is greatly appreciated.
You had a few issues, I would suggest you review this very carefully -
// Why make them public?
private int units = 0;
private int tens = 0;
private int hundreds = 0;
public TestingMenu(int input) {
// Convert it to a String.
String str = String.valueOf(input);
if (str.length() == 1) {
// ones and only ones.
units = Integer.parseInt(str);
} else if (str.length() == 2) {
// tens and ones.
tens = Integer.parseInt(str.substring(0, 1));
units = Integer.parseInt(str.substring(1, 2));
} else if (str.length() == 3) {
// hundreds, tens and ones.
hundreds = Integer.parseInt(str.substring(0, 1));
tens = Integer.parseInt(str.substring(1, 2));
units = Integer.parseInt(str.substring(2, 3));
}
}
// Just use get, PLEASE!
public int getUnits() {
return units;
}
public int getTens() {
return tens;
}
public int getHundreds() {
return hundreds;
}
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
try {
TestingMenu num;
int choice;
do {
System.out.print("Enter a number(0-999): ");
num = new TestingMenu(kbReader.nextInt());
System.out.println("");
System.out.println("Options");
System.out.println("1) Units");
System.out.println("2) Tens");
System.out.println("3) Hundreds");
System.out.println("4) Quit");
System.out.print("Enter your choice: ");
choice = kbReader.nextInt();
if (choice == 1) {
System.out.println("The units digit is: "
+ num.getUnits());
} else if (choice == 2) {
System.out.println("The tens digit is: "
+ num.getTens());
} else if (choice == 3) {
System.out.println("The hundreds digit is: "
+ num.getHundreds());
} else if (choice != 4) {
// We want 4 to fall through and terminate the loop.
System.out.print("Invalid. Select a number "
+ "from the given options.");
choice = kbReader.nextInt();
}
} while (choice != 4);
} finally {
// close the Scanner.
kbReader.close();
}
}
What I would do is I would is I would use your Scanner to take input as a string so you can use .length() to get the length and .charAt() to display them...remember that charAt is like arrays in that the indexes start from 0, length does not. If you need them to be ints you can use Integer.parseInt() (be sure to check it is a number before trying this cause it will throw an exception but with a boolean and a try catch you can continue to ask users for input until they get it right like this
boolean notComplete = true;
while(notComplete = true){
try{ userinput = //get input somehow
Integer.parseInt(userinput);
//do whatever
boolean complete = true;
}catch(NumberFormatException e){
//get input and repeat it will keep trying until the boolean is updated
}})
But for this I don't think it matters how you keep it as long as you display it. You could also add an array of Strings that have indexs that correspond to what they are...meaning something like this:
String[] s = {"ones", "tens", "hundreds"};
so that when the user says 1, 2 or 3 to pick what should be displayed you can subtract one call .charAt on the string to display the number and print the index of the array s at the same index to tell the user what it is.