In this situation I cannot use a for loop or a do while loop. I am in a intro programming class and cannot seem to get anything to work for me, I am in need of some help. What we are having to do is to take a text file make java read it and find out how many left parenthesis, right parenthesis, commas, periods, exclamation points, question mark, asterisk, and how many vowels are in the text file. The problem that I am facing with this is that I cannot seem to get it to update the counters correcting and I also cannot get the input.hasNext() as a variable. Anything helps, thanks in advance.
Code here:
import java.util.Scanner;
import java.io.*;
public class PP5_15
{
public static void main(String[]args) throws IOException
{
Scanner input = new Scanner(new File("Chp5.txt"));
input.useDelimiter("");
int R_ParCount = 0;
int L_ParCount = 0;
int ComCount = 0;
int PerCount = 0;
int ExCount = 0;
int QuCount = 0;
int AstCount = 0;
int VowCount = 0;
int NumCount = 0;
while(input.hasNext() == true)
{
if(input.next().contains("("))
R_ParCount++;
else if (input.next().contains(")"))
L_ParCount++;
}
while(input.hasNext())
{
if(input.next().contains("'"))
ComCount++;
else if(input.next().contains("%"))
PerCount++;
}
System.out.println("Amount of Right Parenthese: "+R_ParCount);
System.out.println("Amount of Left Parenthese: "+L_ParCount);
System.out.println("Amount of Commas: "+ComCount);
System.out.println("Amount of Percent Signs: "+PerCount);
System.out.println("Amount of Exclamation Points: "+ExCount);
System.out.println("Amount of Question Marks: "+QuCount);
System.out.println("Amount of Astric Count: "+AstCount);
System.out.println("Amount of Vowels: "+VowCount);
System.out.println("Amount of Numeric Places are: "+NumCount);
}
}
You just need to store the value returned by next() and then do the comparisons:
input.useDelimiter("");
while(input.hasNext())
{
// Get the next letter and convert to char
char c = input.next().charAt(0);
if (c == '(') {
R_ParCount++;
}
else if (c == ')') {
L_ParCount++;
}
else if (c == ',') {
ComCount++;
}
else if (c == '%') {
PerCount++;
}
// etc...
}
import java.util.Scanner;
import java.io.*;
public class CountChars
{
public static void main(String[]args) throws IOException
{
// fine so far
Scanner input = new Scanner (new File("meanVarianceRange.sh"));
input.useDelimiter("");
// counting everything is more easy, than counting 10 different things
int[] charcount = new int [256];
// except for the vowels, which is aeiou=5 + 5 (uppercase)
int vowels = 0;
// not to mention 10 ciphers, if I understood correctly
int numerics = 0;
while (input.hasNext ())
{
char c = input.next ().charAt (0);
// we use the char as index into our array and just increment
++charcount [c];
// but for the vowels, we count them as group, too
if ("aeiouAEIOU".contains ("" + c))
++vowels;
// in contrast, digits are ordered in the ascii table,
// so we can express them as >= '0' and <= '9'
if (c >= '0' && c <= '9')
++numerics;
}
// see, how the char itself makes the code self commenting:
System.out.println ("Amount of Right Parenthese: " + charcount[')']);
System.out.println ("Amount of Left Parenthese: " + charcount['(']);
System.out.println ("Amount of Commas: " + charcount[',']);
System.out.println ("Amount of Percent Signs: " + charcount['%']);
System.out.println ("Amount of Exclamation Points: " + charcount['!']);
System.out.println ("Amount of Question Marks: " + charcount['?']);
System.out.println ("Amount of Astric Count: " + charcount['*']);
System.out.println ("Amount of Vowels: " + vowels);
// (charcount['a'] + charcount['a'] + charcount['e'] + charcount['i'] + charcount['o'] + charcount['u']));
System.out.println ("Amount of Numeric Places are: " + numerics);
}
}
Since the method 'contains' in String expects a String, we have to use this special transformation from char to String (of length 1), to find our char: .contains ("" + c). Well - there are alternatives, like indexOf and testing for >= 0.
Characters can flawlessly be converted into ints (but not the other way round). That's why we can use the char itself as index into our int-array, which contains as value of charcount['x'] the number of increments, we performed at that index.
Note, that I changed the input file name, to match something on my drive.
Test:
Amount of Right Parenthese: 11
Amount of Left Parenthese: 11
Amount of Commas: 0
Amount of Percent Signs: 1
Amount of Exclamation Points: 1
Amount of Question Marks: 1
Amount of Astric Count: 7
Amount of Vowels: 43
Amount of Numeric Places are: 19
Related
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
In my code I have a variable, points, that increments based on the consanants and vowels in strings inputted. The method parseSentence is supposed to increase points per word but also ignore spaces.
I've tried running a debugger to see where the problem is but the debugger dies when it reaches the for loop in parseSentence. The method makes the point variable's value the word's point value instead of adding it to the variable. What could be causing this?
import java.util.*;
public class WordGolf1 {
public static int points = 1;
public static void main(String[] args) {
String Input;
System.out.println("Enter word: ");
Scanner sc = new Scanner(System.in);
Input = sc.nextLine();
System.out.println("Not enough points. " + (100 - points) + " needed.");
while (points < 100) {
System.out.println("Enter word: ");
Input = sc.nextLine();
parseSentence(Input);
System.out.println(points + ": points");
System.out.println("Not enough points. " + (100 - points) + " needed.");
}
boolean overshot = true;
Loop:
while (overshot = true) {
if (points == 100) {
overshot = false;
break Loop;
}
points = 100 - (points - 100);
System.out.println("Overshot by " + (points - 100) + " points.");
Input = sc.nextLine();
parseSentence(Input);
}
System.out.println("Congratulations you win!");
sc.close();
}
public static int parseSentence(String input) {
String[] pieces = input.split("\\s+");
for (int y = 0; y < pieces.length; y++) {
if (pieces.length > 1) {
if (y == 0) {
parseWord(input);
} else {
parseWord(input, y);
}
} else {
parseWord(input);
}
}
return points;
}
public static int parseWord(String input) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[0].length(); x++) {
if (charList.indexOf(pieces[0].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[0].charAt(x))
!= -1) {
pointsTemp++;
}
}
points = pointsTemp;
return points;
}
public static int parseWord(String input, int number) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[number].length(); x++) {
if (charList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp++;
}
}
points += pointsTemp;
return points;
}
}
You are not using the value returned by the parseSentence method.
Edit: I tried to rewrite this to be as close your original code with making the changes I feel where necessary.
Now Obviously your teacher has requirements and we can't go against that, but some points of interest you should keep in mind.
Multi Splitting
In your example you split the text to get the amount of words. Then instead of looping the already split text. You are sending the original input and then splitting it again. The "Double" splitting is why you needed "three" methods. If you don't double split you can simply loop the length from the single split and just use a single ParseWord method.
Deducting Values
In your example you take away 100 if the player overshot. The problem with this is let's say the person received a score like 200. Then it would loop twice to lower the value submitting the "You overshot message" twice. However let's say by some magical way a score of 100,000,000 was received. Then as you can see we would loop 1 million times to deduct this value essentially creating an not infinite but might as well be infinite loop.
To resolve this problem we simply do the below.
Value = Value % 100.
This will give us the remainder of our Value between 0 and 99. I.e. 167 will equal 67 and 12384 will be equal 84.
Using String (IndexOf)
What this does is takes the Character you provided and loop iterates over the String you provided. The worst case is 12 loops. There's also a lot of other stuff String and IndexOf do that is extra work and I recommend staying away from it if you can.
The alternative solution which I did is take the character and use " | 32" on it. I'm not going to go deep into how bits work, but basically these characters are 8 bit values but we only use 7 of it's bits ranging from 32 to 127. The amount of bits is like the power of 2. so 2^7 = 128 and 2^8 = 256. When we perform the "|" we are turning a bit on so if it's already on it won't change the value.
So in our example let's say we have the value 64.
This is bit 6 turned on. Now we want to turn on bit 5 "32" so the value becomes 96, but if we already had the value 96 and we turn bit 32 on it will still be 32.
Full List of ASCII Characters..
https://www.ascii-code.com/
The Game Loop
In your example you created "TWO" game loops the first one is when you start off, but once you overshot your score you enter the second loop and forget the first one. The problem is now your "Enter Words" and "You Undershot" code are never used anymore. So all someone will see is the line to enter text with no information on what to do or what occurred unless they overshot then they get the overshot message.
To fix this I made a single Game Loop which processes until the code ends via the SCORE == 100. You can see in the code that we begin every game loop with "Enter Words: " and parse the sentence. Then we add up our score and compare. If we undershot we simply restart the loop and try again. If we overshot we reduce the score and try again. If we succeeded we prompt the user if they would like to play again or end the game. Playing again will set the SCORE to 0 and start over the loop. Ending the game will "BREAK" the loop and cause it to end.
The Full Working Code With Recommended Changes
Feel free to comment if you need additional assistance.
import java.util.*;
public class WordGolf1
{
private static int SCORE = 0;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (true)
{
System.out.print("\n\nEnter word: ");
ParseSentence(sc.nextLine());
if (SCORE == 100)
{
System.out.print("\nYou Won! Would you like to play again: Y/N?");
if ((sc.nextLine().charAt(0) | 32) == 'y')
{
SCORE = 0;
System.out.print("\nResetting Game...");
} else {
break;
}
}
else
{
if (SCORE > 100)
{
int overshot = SCORE - 100;
SCORE = SCORE % 100;
System.out.print("\nYou Overshot By " + overshot + " Points. You now have " + SCORE + " points.");
} else {
System.out.print("\nYou currently have " + SCORE + " points you need " + (100 - SCORE) + " more.");
}
}
}
}
private static int ParseSentence(String input)
{
String[] split = input.split(" ");
for (Strng s : input)
SCORE += ParseWord(s);
}
private static int ParseWord(String word)
{
int value = 1;
for (int i = 0; i < word.length(); ++i)
{
int c = (int)word.charAt(i) | 32;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
value *= 2;
} else {
value += 1;
}
}
return value;
}
}
So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1
I am trying to figure out how to find the percent difference between the original (no space) string of text and the disemvoweled (no space) string of text. I am attempting to do this by using the equation ((newAmount-reducedAmount)/reducedAmount) but I am having no luck and am ending up with a value of zero, as shown below.
Thank you!
My Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
System.out.println("Welcome to the disemvoweling utility!"); // Initially typed "disemboweling" xD
System.out.print("Enter text to be disemvoweled: ");
String inLine = console.nextLine();
String vowels= inLine.replaceAll("[AEIOUaeiou]", ""); // RegEx for vowel control
System.out.println("Your disemvoweled text is: " + vowels); // Prints disemvoweled text
// Used to count all characters without counting white space(s)
int reducedAmount = 0;
for (int i = 0, length = inLine.length(); i < length; i++) {
if (inLine.charAt(i) != ' ') {
reducedAmount++;
}
}
// newAmount is the number of characters on the disemvoweled text without counting white space(s)
int newAmount = 0;
for (int i = 0, length = vowels.length(); i < length; i++) {
if (vowels.charAt(i) != ' ') {
newAmount++;
}
}
int reductionRate = ((newAmount - reducedAmount) / reducedAmount); // Percentage of character reduction
System.out.print("Reduced from " + reducedAmount + " to " + newAmount + ". Reduction rate is " + reductionRate + "%");
}
}
My output: (Test string is without quotes: "Testing please")
Welcome to the disemvoweling utility!
Enter text to be disemvoweled: Testing please
Your disemvoweled text is: Tstng pls
Reduced from 13 to 8. Reduction rate is 0%
You used an integer data type while calculating percentage difference while performing integer division. You need to type cast one of the variables on the right hand side of the equation to perform double division and then store them in double. The reason for doing this is java integer type can't hold the real numbers.
Also, multiple it by 100 to get the percentage.
double reductionRate = 100 * ((newAmount - reducedAmount) / (double)reducedAmount);
If you want a fraction between 0 and 1, then
double reductionRate = ((newAmount - reducedAmount) / (double)reducedAmount);
Your formula gives you a value between zero and one.
An integer cannot hold fractions so it always shows zero.
Multiply by 100 to get a regular percentage value.
int reductionRate = 100*(newAmount - reducedAmount) / reducedAmount; // Percentage of character reduction
I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.