I wrote a program that counts the total number of occurrences of some substring in a string
But there can be many lines in the text
Now there are 3 lines in the text, and the program outputs a value for each of the lines
The code outputs 3 numbers, although I need one, which is how to fix it? another cycle?
public class OccurrencesAmount {
public static int getOccurrencesAmount(String substring, String string) {
substring = substring.toUpperCase();
string = string.toUpperCase();
int count = 0;
int fromIndex = 0;
int length = substring.length();
while (true) {
int occurrenceIndex = string.indexOf(substring, fromIndex);
if (occurrenceIndex < 0) {
break;
}
count++;
fromIndex = occurrenceIndex + length;
}
return count;
}
public static void main(String[] args) throws FileNotFoundException {
try (Scanner scanner = new Scanner(new FileInputStream("input.txt"))) {
String searchLine = "о";
while (scanner.hasNextLine()) {
System.out.println(
getOccurrencesAmount(searchLine, scanner.nextLine()));
}
}
}
}
At the moment your program outputs for every single line.
Your method is already returning an int-value. So to get the total amount of occurences over all lines, you just need to sum them up like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String searchLine = "о";
int totalOccurences = 0;
while (scanner.hasNextLine()) {
totalOccurences += getOccurrencesAmount(searchLine, scanner.nextLine());
}
System.out.println(totalOccurences);
}
}
Related
I have file of which I need to read input. On one of the lines, there is no name added. In this case, I want to print out that no match was found. The problem that I'm having is that I don't know how I can make sure the program actually reads the part as an empty string. What happens now is that the will just leave the line empty on the console.
The date input looks like this:
5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan
2=30=15=8=4=3=2=0=0=0;
class Administration {
public static final int TOTAL_NUMBER_OF_SIMULARITY_SCORES = 10;
public static final String ZERO_MATCHES = "_";
public static final String LESS_THAN_TWENTY_MATCHES= "-";
public static final String TWENTY_OR_MORE_MATCHES = "^";
PrintStream out;
Administration() {
out = new PrintStream(System.out);
}
void printSimilarityScores (Scanner similarityScoresScanner, String similarityScoresInput) {
similarityScoresScanner.useDelimiter("=|;");
int length = similarityScoresInput.length();
for (int i = 0; i < TOTAL_NUMBER_OF_SIMULARITY_SCORES; i++) {
int grade = similarityScoresScanner.nextInt();
if (grade == 0) {
out.printf(ZERO_MATCHES);
} else if (grade < 20) {
out.printf(LESS_THAN_TWENTY_MATCHES);
} else {
out.printf(TWENTY_OR_MORE_MATCHES);
}
}
System.out.print("\n");
similarityScoresScanner.useDelimiter(";|,");
while(similarityScoresScanner.hasNext()) {
String name = similarityScoresScanner.next();
if (length < 22) {
out.printf("No matches found\n");
} else {
System.out.print("\n" + name);
}
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
while (fileScanner.hasNext()) {
String finalGradeInput = fileScanner.nextLine();
String similarityScoresInput = fileScanner.nextLine();
Scanner finalGradeInputScanner = new Scanner(finalGradeInput);
Scanner similarityScoresScanner = new Scanner(similarityScoresInput);
printFinalGrade(finalGradeInputScanner);
printSimilarityScores(similarityScoresScanner, similarityScoresInput);
}
}
public static void main(String[] argv) {
new Administration().start();
}
}
An easier solution would be to read the file, line by line and handle them like this :
split by the separator
check if there is more than 1 element,
if positive print them
Scanner similarityScoresScanner = new Scanner(myFile);
while (similarityScoresScanner.hasNextLine()) {
String[] content = similarityScoresScanner.nextLine().split("[;,]");
if (content.length == 1) {
System.out.println("No matches found");
} else {
for (int i = 1; i < content.length; i++) {
System.out.println(content[i]);
}
}
}
The problem is my spellchecker, that I am trying to make. I have a dictionary file that contains large amount of words to compare with the user input so it can detect any possible spelling errors. The problem with mine, is that regardless of what you type it will always say that the spelling is incorrect when it is not. Is there any solution or a better method to detect selling errors of the user input.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SpellChecker2 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String");
String userWord = input.nextLine();
final String theDictionary = "dictionary.txt";
String[] words = dictionary(theDictionary);
boolean correctSpelling = checking(words, userWord);
if (!correctSpelling)
{
System.out.println("Incorrect spelling");
}
else
{
System.out.println("The spelling is correct");
}
}
public static String[] dictionary(String filename) throws FileNotFoundException
{
final String fileName = "dictionary.txt";
Scanner dictionary = new Scanner(new File(fileName));
int dictionaryLength =0;
while (dictionary.hasNext())
{
++dictionaryLength;
dictionary.nextLine();
}
String [] theWords = new String[dictionaryLength];
for ( int x = 0; x < theWords.length ; x++)
dictionary.close();
return theWords;
}
public static boolean checking(String[] dictionary, String userWord)
{
boolean correctSpelling = false;
for ( int i =0; i < dictionary.length; i++)
{
if (userWord.equals(dictionary[i]))
{
correctSpelling = true;
}
else
correctSpelling = false;
}
return correctSpelling;
}
}
The result I get is:
Please enter a String
hello
Incorrect spelling
As you can see the, even though my spelling was correct, it gives an error that the spelling was incorrect. Any help would be great and thank you in advance.
Yes. Return from checking on true. As you have it now, it can only be true if the last word matches. Like,
public static boolean checking(String[] dictionary, String userWord) {
for ( int i =0; i < dictionary.length; i++) {
if (userWord.equals(dictionary[i])) {
return true;
}
}
return false;
}
Also, you need to populate your dictionary by adding words to your array.
And, I would prefer try-with-resources over explicit close() calls. Something like,
public static String[] dictionary(String filename) throws FileNotFoundException {
final String fileName = "dictionary.txt";
int dictionaryLength = 0, i = 0;
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
++dictionaryLength;
dictionary.nextLine();
}
}
String[] theWords = new String[dictionaryLength];
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
theWords[i] = dictionary.nextLine();
i++;
}
}
return theWords;
}
I have a program that takes in a file of unindented code and comments the program takes the specified file and will output an indented version of the code.
I keep on getting the java.lang.ArrayIndexOutOfBoundsException: 1 error. This seems to occur when I have only one comment on a line as for when it splits the string the index only takes up 0. I have got an if statement in place to handle a comment on a line on its own but it still throws the exception.
Would I need to implement an if statement to check whether or not the split string has more than 1 part to it?
import java.io.*;
import java.util.*;
class Program
{
public static int spaces = 0;
public static int longestLine = 0;
public static int commentSpaces;
public static String beforeComment;
public static String afterComment;
public static void main(String args[]) throws FileNotFoundException
{
Scanner input2 = new Scanner(new File("C:\\Users\\James\\Music\\code.java")); //get text from file
while (input2.hasNextLine() == true) { //get the longest line
String text = input2.nextLine();
if (text.contains("//")) {
if (text.contains("\"//")) {
printLine(text);
}
String[] parts = text.split("//");
String codeOnly = parts[0];
if (codeOnly.length() > longestLine) {
longestLine = codeOnly.length();
}
}
else {
if (text.length() > longestLine) {
longestLine = text.length();
}
}
if (input2.hasNextLine() == false) {
break;
}
}
Scanner input3 = new Scanner(new File("C:\\Users\\James\\Music\\code.java"));
while (input3.hasNextLine()) { //indent comments
String text = input3.nextLine();
if (text.contains("}")) {
spaces -=2;
}
for (int i = 0; i < spaces; i++) {
System.out.print(" ");
}
if (text.startsWith("//")){
String justComment = text;
commentSpaces = longestLine - spaces + 6;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(justComment);
System.out.println(" ");
}
if (text.contains("\"//")) {
printLine(text);
}
if (text.contains("//")) {
String[] parts = text.split("(?=//)");
beforeComment = parts[0].trim(); // trim() to get rid of any spaces that are already present within the code
afterComment = parts[1];
printLine(beforeComment);
commentSpaces = longestLine - beforeComment.length() - spaces + 5;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(afterComment);
System.out.println();
}
else {
printLine(text);
System.out.println();
}
if (text.contains("{")) {
spaces +=2;
}
}
}
public static void printLine(String text) {
Scanner data = new Scanner(text);
while (data.hasNext()) {
System.out.print(" " + data.next());
}
}
public static void yesItContains() {
System.out.print("It contains a string");
System.exit(0);
}
}
I think that if text is "something//" meaning it is ending in a empty comment your parts will only have length 1. So yes, you need to check it, e.g. via afterComment = parts.length > 1 ? parts[1] : "";. Note that lines like "something // something else // blabla" might break that logic as well.
I want to split a String into n number of characters.
Consider input to be "Example-for-my-Question". Now if I want to split into n=3 characters, output should be "Exa, mpl, e-f, or-, my-, Que, sti, on" and suppose n=4, output should be "Exam, ple-, for-, my-Q, uest, ion" How can you modify the program below without using POSIX.
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String; ");
String inputString = in.nextLine();
System.out.println("How many characters do you want to split into ?");
int n = in.nextInt();
String[] array = inputString.split(" ", n);
System.out.println("Number of words: " + array.length);
for (String arr : array)
System.out.println(arr);
}
}
The simple way to do this is to use String.substring(...) repeatedly to trim N characters off the front of your string ... in a loop.
But if you really want to do this using String.split(...), then I think that the separator regex needs to be a positive look-behind that matches N characters. (It is obscure, and inefficient ... but if regexes are your universal tool ...)
You can use substring for this task.
String sp="StackOverFlow";
int NoOfChars=3;
for(int i=0;i<sp.length();i+=NoOfChars)
{
if(i+NoOfChars<=sp.length())
System.out.println(sp.substring(i,i+NoOfChars));
//Instead add in String ArrayList
else
System.out.println(sp.substring(i));
}
OUTPUT
Sta
ckO
ver
Flo
w
NOTE:Better to use trim() to remove leading or trailing spces
This works for me. In addition to splitting into known lengths, it checks for a null or "too small of a" source string, etc. If a null string is supplied, then a null is returned. If the source string is smaller than the requested split length, then the source string is simply returned.
public static void main (String[] args) throws java.lang.Exception
{
// Three test cases...
String pieces[] = SplitString("Example-for-my-Question", 3);
//String pieces[] = SplitString("Ex", 3);
//String pieces[] = SplitString(null, 3);
if (null != pieces)
{
for (int i = 0; i < pieces.length; i++)
{
System.out.println(pieces[i]);
}
}
}
private static String[] SplitString(String source, int size)
{
String result[] = null;
if (null != source && source.length() > size)
{
int numberOfElements = source.length() / size;
int modulo = source.length() % size;
if (modulo > 0)
{
numberOfElements++;
}
result = new String[numberOfElements];
for (int i = 0; i < numberOfElements; i++)
{
if (numberOfElements - 1 != i)
{
result[i] = source.substring(i * size, (i * size) + size);
}
else
{
result[numberOfElements - 1] = source.substring(i * size, (i * size) + modulo);
}
}
}
else if (null != source)
{
result = new String[1];
result[0] = source;
}
return result;
}
Please try the following program, but here you have to give input to "N" inside the program itself
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}
This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?
public class Capitalize
{
public static void capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println(scanner.next());
}
}
Problems as I see them:
The code as it stands will only print the first word typed in once the user presses enter
The method doesn't return anything, so effectively it does all that work and discards it.
So here is what I might do:
I'm going to put everything in main for the sake of concision
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String sentence = Scanner.nextLine();
StringBuilder ans = new StringBuilder(); // result
for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
if(str.Length>0) // can happen if there are two spaces in a row I believe
str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
ans.Append(str); // add modified word to the result buffer
ans.Append(' '); // add a space
}
System.out.println(ans);
}
}
You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight
I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.
`public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext())
System.out.println(scanner.next());
}`
I would probably do this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { // While there is input.
String line = scanner.nextLine(); // read a line.
int i = 0;
for (String s : line.split(" ")) { // split on space... word(s).
if (i != 0) {
System.out.print(" "); // add a space, except for the first word on a line.
}
System.out.print(capCase(s)); // capCase the word.
i++; // increment our word count.
}
System.out.println(); // add a line.
System.out.flush(); // flush!
}
}
public static String capCase(String theString) {
if (theString == null) {
return ""; // Better safe.
}
StringBuilder sb = new StringBuilder(theString
.trim().toLowerCase()); // lowercase the string.
if (sb.length() > 0) {
char c = sb.charAt(0);
sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
}
return sb.toString(); // return the word.
}
Problem :
1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.
Solution
1.use the below statement to read complete Line
String str=scanner.nextLine();
2.Change return type of capCase() from void to char[] as below:
public static char[] capCase(String theString)
you should return the char[] variable chars from capCase() function as below:
return chars;
Complete Code:
public static char[] capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
return chars;
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
System.out.println(capCase(str));
}
Try,
public static void main(String[] args) {
System.out.println(capCase("hello world"));
}
public static String capCase(String theString) {
StringBuilder res = new StringBuilder();
String[] words=theString.split(" +");
for (String word : words) {
char ch=Character.toUpperCase(word.charAt(0));
word=ch+word.substring(1);
res.append(word).append(" ");
}
return res.toString();
}
Try this code it worked for me:
import java.util.Scanner;
public class Capitalize {
/**
* This code should allow the user to input a sentence, change it to lower
* case, and then capitalize the first letter of each word. But I can't get
* the scanner to work, it just prints nothing. Any suggestions?
*
* #param theString
*/
public static void capCase(String theString) {
String source = theString.trim();
StringBuffer res = new StringBuffer();
String lower = theString.toLowerCase();
String[] split = lower.split(" ");
for (int i = 0; i < split.length; i++) {
String temp = split[i].trim();
if (temp.matches("^[a-zA-Z]+")) {
split[i] = temp.substring(0, 1).toUpperCase()
+ temp.substring(1);
}
res.append(split[i] + " ");
}
System.out.println(res.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
capCase(scanner.nextLine());
// System.out.println(scanner.next());
}
}
I've tested it. It works.
import java.util.Scanner;
import org.apache.commons.lang3.text.WordUtils;
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
System.out.println(WordUtils.capitalize(s.nextLine()));
}
}
}