while (scan.hasNextLine()) {
String thisline = scan.nextLine();
totalnumber.countthelines++; //linecount works
for(int i = 0; i < thisline.length();i++){
totalnumber.charactercounter++; //chararacter count works
String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length; //does not work
}
}
I am having trouble getting my wordcounter to work(I am already able to count the characters and lines). I have tried many different ways to make it work, but it always ends up only counting the words from the last line of the read in file. Any suggestions on how to make it read every single line instead of just the last?
Thanks
Well :
totalnumber.wordcounter += thewords.length
should be enough !
You just forgot to add the number of words...
So the entiere code is :
while (scan.hasNextLine()) {
String thisline = scan.nextLine();
totalnumber.countthelines++; //linecount works
totalnumber.charactercounter+=thisline.length(); //chararacter count works
String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;
}
(Sorry about the multiple edits. Sometime, it's so obvious... ;)
You need:
String [] thewords = thisline.split (" ");
totalnumber.wordcounter += thewords.length;
outside of the loop iterating the characters. Note the += instead of =.
for(int i = 0; i < thisline.length(); i++) {
totalnumber.charactercounter++; //chararacter count works
}
String [] thewords = thisline.split (" ");
totalnumber.wordcounter = thewords.length; //does not work
Related
So I am asked to write a program that reads a sentence from the user, reports and removes wrong repetitions if any. By wrong repetitions I mean that a word (or more) is repeated (two occurrences or more) and that these repetition are consecutive.
`
public class checker {
private String sentence;
checker(String sentence){this.sentence=sentence;}
public String check(){
String[] word = sentence.split(" ");
for(int i=0; i<word.length; i++){
for(int j=i+1; j<word.length; j++){
if(word[i].equals(word[j])){
word[j]="error";}}}
for(int i=0; i<word.length; i++) {
if (!"error".equals(word[i])) {
System.out.print(word[i] + " ");}}
return "";}
}
***This is the output of my code: ***
Enter a Sentence: The operator did not not skip his meal
The operator did not skip his meal
BUILD SUCCESSFUL (total time: 12 seconds)
So my code does the job of finding the repeated words and prints the corrected version, but the problem is that I just can't find a way to make it print out like it is supposed to do in the sample run!
[Sample runs:
-Enter a sentence: The operator did not not skip his meal
-The sentence includes wrong repetitions.
-The sentence should be: The operator did not skip his meal
-Enter a sentence: Happy people live longer
-There are no wrong repetitions]
**I do know my problem, every time I try to write a piece of code containing any time type of loops and if statements together I just don't know to extract what I want from the loop and conditional statements, I was trying to
`
for(int i=0; i<word.length; i++){
for(int j=i+1; j<word.length; j++){
if(word[i].equals(word[j])){
System.out.println("The sentence includes wrong repetitions.\nThe sentence should be: ");
word[j]="error";}
else{
System.out.println("There are no wrong repetitions");
}
}
}
`
but I know it'll print it every time the loop gets executed!
I would really appreciate a helpful tip that I can carry with me going forward!
Thanks in advance guys!**
You don't have any mechanism by which to store your valid words so you can print them in the format you need to after your sentence evaluation is complete. I recommend storing the valid words in a StringBuilder or ArrayList as you go so you can print the resulting string when you are ready.
Here is a sample program to accomplish this using a StringBuilder. You could also use an ArrayList and call String.join(" ", wordList); to create the sentence when finished.
final String sentence = "This is an invalid invalid sentence that that needs corrected";
final String[] words = sentence.split(" ");
StringBuilder sentenceBuilder = new StringBuilder();
for (int i = 0; i < words.length; i++)
{
final String checkWord = words[i];
final boolean lastWord = i == words.length - 1;
final boolean duplicate = !lastWord && checkWord.equals(words[i + 1]);
if (lastWord || !duplicate)
sentenceBuilder.append(checkWord);
if (!lastWord && !duplicate)
sentenceBuilder.append(' ');
}
if (!sentence.equals(sentenceBuilder.toString()))
System.out.printf("The sentence includes wrong repetitions.%nThe sentence should be: %s%n", sentenceBuilder);
else
System.out.println("There are no wrong repetitions");
I faced the same problem in my assignment last week. I couldn't solve it but I had to submit something so I don't get a zero. The errors in my program is that there is a space left in place of the duplicated word, and it only detects two occurrences.
Here's the code i wrote:
String [] n= s.split(" ");
boolean check=false;
for (int i=1;i<n.length;i++){
String temp=n[i-1];
if (n[i].equals(temp) == true) {
check = true;
System.out.println("The sentence includes wrong repetitions.");
n[i]="";
System.out.print("The sentence should be: ");
for(int j=0;j<n.length;j++) {
System.out.print(n[j]+" ");
}
}
}
if (check == false)
System.out.println("There are no wrong repetitions");
}
}
Let me know if you found the solution or if you can improve my code
The insturctor sent us the solution, adding it here for future reference:
/*
CSCI300 - Solution of Assignment 1
Problem 2
*/
package repetitions;
import java.util.Scanner;
public class Repetitions {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean hasSuccessiveReptition = false; //Assume no repetitions
System.out.print("Enter a sentence: ");
// Read the whole sentence into one String:
String sentence = scan.nextLine();
//create an array of Strings to handle each word separately
String[] words = sentence.split(" ");
//Create a string to add non repetetive words to
String repetitionFreeSentence = words[0]; // add the fisrt word
for(int i = 1; i < words.length; i++)
if(words[i].equalsIgnoreCase(words[i-1])) // compare successive words
hasSuccessiveReptition = true;
else // add the word to the corrected setence
repetitionFreeSentence += " " + words[i];
if(hasSuccessiveReptition){
System.out.println("The sentence includes wrong repetitions.");
System.out.println("The sentence should be: " + repetitionFreeSentence);
}
else
System.out.println("There are no wrong repetitions");
}
}
I have a string that I split based on delimiter on new lines. I'm wondering now how to check the first word index[0] what word is but can't find a way to actually go trough the elements and check.
May be my approach is totally wrong.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
int ask = 0;
for (int i = 0; i < stringArr.length; i++) {
if (stringArr[0].equals("radio")) {
ask = 10;
} else if (Objects.equals(stringArr[0], "tv")) {
ask = 15;
} else {
System.out.println("Invalid media.");
}
}
System.out.println(ask);
}
Then when I input radio 3 7210>>tv 4 2345>>radio 9 31000>>
The output should be:
10
15
10
Instead - got nothing. Empty line and the program ends.
Is something like this what you want:
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
String[] stringArr = line.split(">>");
for (int i = 0; i < stringArr.length; i++) {
int ask = 0;
String[] words = stringArr[i].split(" ");
if (words[0].equals("radio")) {
ask = 10;
System.out.println(ask);
} else if (words[0].equals("tv")) {
ask = 15;
System.out.println(ask);
} else {
System.out.println("Invalid media.");
}
}
Input:
radio 3 7210>>tv 4 2345>>radio 9 31000>>
Output:
10
15
10
First of all, I defined the scanner, not sure if you did that but pretty sure you did.
The elements of stringArr will include the random numbers between each ">>". That means, in each element, we should create a new list split by " " to isolate the "radio" and "tv" as the first element.
Additionally, I just rewrote the else-if statement that checks if the first word of the phrases separated by ">>" is "tv" by using the .equals() method as your original if statement did.
Finally, since you are printing out a number EACH time the code encounters a ">>", we should print out ask inside of the for loop.
EDIT:
Moved the System.out.println(ask) inside of the if and else-if statements so it will only run with valid media.
Other than that your code worked perfectly :> , let me know if you have any further questions or clarifications!
I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);
I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.
I am trying to get my Java program to accept blank lines of text as input, as well as displaying them in the final output.
Basically I have made a word scrambling program, that is supposed to take in an unspecified amount of text from the Scanner, scrambling each word individually except for the first and last letters of each word. I have successfully gotten the scrambling and parsing to work, so no worries there. The last spec that I'm working on, is the fact that the user may hit the "return" button entering in a blank line of text.
So, for example, if someone were to enter:
Pizza is my favorite thing to eat
The output would be something like:
Pziza is my fovaitre tnhig to eat
That works perfectly on one line, but if someone were to enter:
I
Like
Animals
Only the last line gets printed and scrambled:
aimnlas
I have tried a few different suggestion I found through research, but most are suggestions for file reading and other things that haven't worked out for me.
This is what I'm doing now:...
Scanner input = new Scanner(System.in);
String text = "";
System.out.println("Enter text to scramble: ");
while(input.hasNextLine()){
text = input.next();
}
System.out.println(scramble(text));
Any help would be greatly appreciated. Thanks everyone =)
EDIT:
OK I'm thinking something I did in my scramble method may be what's preventing me from allowing blank lines. I've looked it over and can't seem to pinpoint it, so if someone could please take a look and let me know what you think I would appreciate it =)
private static String scramble(String txt) {
StringTokenizer st = new StringTokenizer(txt, " ,.!?()-+/*=%##$&:;\"'", true);
String[] tokens = new String[st.countTokens()];
String scrambled = "";
int letter = 0;
int wordlength = 0;
char[] temp;
while(st.hasMoreTokens()) {
tokens[letter] = st.nextToken();
letter++;
}
for(int i = 0; i < tokens.length; i++) {
if(tokens[i].length() <= 3) {
scrambled += tokens[i];
continue;
}
wordlength = tokens[i].length() - 1;
temp = new char[wordlength + 1];
temp[0] = tokens[i].charAt(0);
temp[wordlength] = tokens[i].charAt(wordlength);
ArrayList<Character> c = new ArrayList<Character>();
for(int j = 1; j < wordlength; j++) {
c.add(tokens[i].charAt(j));
}
Collections.shuffle(c);
String z = new String();
for(Character x:c){
z += x.toString();
}
String output = new String(temp[0] + z + temp[wordlength]);
scrambled += output;
}
return scrambled;
}
When reading from System.in, you are reading from the keyboard, by default, and that is an limitless input stream so Scanner.hasNextLine() will always return true.
One solution is to read one line at a time and split each line into words using String.split():
Scanner input = new Scanner(System.in);
String text = "";
System.out.println("Enter text to scramble: ");
boolean done = false;
while (!done) {
text = input.nextLine();
if (text.equals("")) {
done = true;
} else {
performScramble(text);
}
}
...
void performScramble(String line) {
String[] words = line.split("\\s+");
for (String word: words) {
System.out.println(scramble(word));
}
}