class Main{
public static void main (String str[]) throws IOException{
Scanner scan = new Scanner (System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ "," ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0,0,0};
Getting the error, "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" , in one of the for loops. I want the program to check for each substring in the sWord array and count how many times it occurs in the main message input.
for (int x = 0; x < sWords.length; x++){
for (int i = 0, j = i + sWords[x].length(); j < message.length(); i++){
if ((message.substring(i,j)).equals(sWords[x])){
count[c]++;
}
}
}
}
}
Following your approach, you need to set the value of jwithin the inner loop. Otherwise, it is only assigned on the first iteration. This changes the upper bound in the inner for loop as shown below. You also need to increment the counter index c after you search for an sWord.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int x = 0; x < sWords.length; x++) {
for (int i = 0; i <= message.length()-sWords[x].length(); i++) {
int j = i + sWords[x].length();
if ((message.substring(i, j).equals(sWords[x]))) {
count[c]++;
}
}
++c;
}
}
}
You can find number of occurrences of each string in sWords in the code below:
public static void main(String[] args) {
try {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int i = 0; i < lenOfArray; i++) {
while (c != -1) {
c = message.indexOf(sWords[i], c);
if (c != -1) {
count[i]++;
c += sWords[i].length();
}
}
c = 0;
}
int i = 0;
while (i < lenOfArray) {
System.out.println("count[" + i + "]=" + count[i]);
i++;
}
} catch (Exception e) {
e.getStackTrace();
}
}
It's better to use apache commons lang StringUtils
int count = StringUtils.countMatches("a.b.c.d", ".");
Related
package Fibonacci;
class Fibonacci
{
public static void main(String[]args) {
int a = 0;
int b = 1;
String input;
input = javax.swing.JOptionPane.showInputDialog("How many elements you want to print in a Fibonacci series");
int n = Integer.parseInt(input);
javax.swing.JOptionPane.showMessageDialog(null, a + " "+ b + " ");
int c;
for(int i = 2; i < n; i++) {
c = a + b;
javax.swing.JOptionPane.showMessageDialog(null, c + " ");
a = b;
b = c;
}
}
}
// Here is the code ? what can I change to display the output on only one dialogbox? Sorry I'm just new with learning java,
You should first collect the data which you want to print in a DialogBox.
Then you can print the data with the DialogBox (not in the for loop).
Take a look at following code.
import javax.swing.*;
public class main {
public static long fibonacci(int n){
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
b = a + (a = b);
}
return a;
}
public static void main(String... args){
int input = Integer.parseInt(JOptionPane.showInputDialog("Number of print elements"));
String fib = "";
for (int i = 0; i <= input; i++) {
fib = fib + fibonacci(i) + "\n";
}
JOptionPane.showMessageDialog(null, fib);
}
}
i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(input.readLine());
for (int i = 0; i < t; i++) {
String[] arrayData = input.readLine().split(" ");
int[] cardsi = new int[arrayData.length];
int e = 0;
for(int a = 0; a < arrayData.length; a++){
cardsi[e] = Integer.parseInt(arrayData[a]);
e++;
}
int X = cardsi[0];
int N = cardsi[1];
long count = 0;
for (int j = 2; j < cardsi.length; j++) {
for (int l = 3; l <= (cardsi.length - 1); l++) {
if ((cardsi[j] + cardsi[l]) == X &&(j != l)) {
count++;
}
}
}
System.out.println((i + 1) + ". " + count);
}
}
}
Time limit exceeded error is appearing upon submitting this LCPC12F problem on spoj.. what might be a solution? Is scanner a major trouble for such error to appear?
Have you ever run those codes on IDE?
When I give the number to t element then arrayData (in this case, we should enter int type not String, because of the java.lang.NumberFormatException), it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 and int N = cardsi[1]; is the main problem on your code I think. This is because String[] arrayData = input.readLine().split(" "); size is 1 so you do not have cardsi[1] element on your int array
I am developing a program that will search through my array for how many times my single random # appears and then print how many times or that it was not found. I have been researching ways to do this and cannot seem to get it figured out. This is what I have so far and thanks in advance.
My code:
import java.util.Scanner;
import java.util.Random;
class Main {
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++) {
System.out.println("Single Random # " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public int findNumInstancesInArray(int[] array, int numLookingFor) {
int count = 0;
for(int i : array) {
if (i == numLookingFor) {
count++;
}
}
return count;
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numLookingFor = RND_GEN.nextInt(10) + 1;
System.out.println("Number of instances of " + numLookingFor + " is: " + findNumInstancesInArray(numbers, numLookingFor));
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
This is how you can count an element in an int array:
public int countOccurrences(int[] array, int needle) {
int count = 0;
for (int index = 0; index < array.length; array[++index] == needle ? count++ : count);
return count;
}
It seems as if this is the search part of your other question posted here: Random number and array search
There, you were suggested to learn about linear search and binary search. If you did, it shouldn't be too hard to translate linear search into code (binary search won't help you here). You simply have to loop through the array (you're code proves you know how to do that) and check every value if it equals the one you're searching for. Of course, if you want to count the hits, you have to increase a counter every time the value matches.
I am trying to count the amount of times a word is repeated in stdin.
Example input:
This is a test, this is is
Desired output:
this 2
is 3
a 1
test 1
I have an int[] to store the wordCount but I'm not sure where to use it, the int count is just temporary so the program can run.
Here is my code for reference:
import java.util.Scanner;
public class WCount {
public static void main (String[] args) {
Scanner stdin = new Scanner(System.in);
String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;
while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\\
s+"); //stores strings as words after converting to lowercase and getting rid of punctuation
for(int i = 0; i < words.length; i++){
int count = 0; //temporary so program can run
for(int j = 0; j < words.length; j++){
if( words[i] == words[j] )
count++;
System.out.println("word count: → " + words[i] + " " + count);
}
}
}
I would use something like this:
import java.util.ArrayList;
import java.util.Scanner;
public class WCount {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String[] wordArray = new String[10000];
int[] wordCount = new int[10000];
int numWords = 0;
while (stdin.hasNextLine()) {
String s = stdin.nextLine();
ArrayList<String> noDuplicated = new ArrayList<String>();
String[] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase()
.split("\\s+"); // stores strings as words after converting
// to lowercase and getting rid of
// punctuation
//Array that contains the words without the duplicates ones
for (int i = 0; i < words.length; i++) {
if(!noDuplicated.contains(words[i]))
noDuplicated.add(words[i]);
}
//Count and print the words
for(int i=0; i<noDuplicated.size();i++){
int count = 0;
for (int j = 0; j < words.length; j++) {
if (noDuplicated.get(i).equals(words[j]))
count++;
}
System.out.println("word count: → " + words[i] + " "
+ count);
}
}
}
}
output:
This is a test, this is is
word count: → this 2
word count: → is 3
word count: → a 1
word count: → test 1
Hope it is usefull!
This works for me. Although iterating through the complete possible array is silly. It would work easier with ArrayList. But as I am not sure if you are allowed to use it.
import java.util.Scanner;
public class WCount {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int[] wordCount = new int[1000];
String[] wordList = new String[1000];
int j = 0;
while (stdin.hasNextLine()) {
String s = stdin.nextLine();
String[] words = s.split("\\W+");
for (String word : words) {
int listIndex = -1;
for (int i = 0; i < wordList.length; i++) {
if (word.equals(wordList[i])) {
listIndex = i;
}
}
if (listIndex > -1) {
wordCount[listIndex]++;
} else {
wordList[j] = word;
wordCount[j]++;
j++;
}
}
for (int i = 0; i < j; i++) {
System.out.println("the word: " + wordList[i] + " occured " + wordCount[i] + " time(s).");
}
}
}
}
output:
this is a test. this is cool.
the word: this occured 2 time(s).
the word: is occured 2 time(s).
the word: a occured 1 time(s).
the word: test occured 1 time(s).
the word: cool occured 1 time(s).
You can use a hash table here. I am not going to write code for you, but here is simple pseudo algorithm:
if hashTable contains word
hashTable.put(word, words.value + 1)
else hashTable.put(word, 1)
Do this for each word in the word array. After all the words have been handled, you simply print each key (word) in the hash table with its value (number of times it appeared).
Hope this helps!
figured this out...simpler way..
import java.util.Vector;
public class Get{
public static void main(String[]args){
Vector<String> ch = new Vector<String>();
String len[] = {"this", "is", "this", "test", "is", "a", "is"};
int count;
for(int i=0; i<len.length; i++){
count=0;
for(int j=0; j<len.length; j++){
if(len[i]==len[j]){
count++;
}
}
if(count>0){
if(!ch.contains(len[i])){
System.out.println(len[i] + " - " + count);
ch.add(len[i]);
}
}
}
}
}
Output:
this - 2
is - 3
test - 1
a - 1
My implementation:
public static void main(final String[] args) {
try (Scanner stdin = new Scanner(System.in)) {
while (stdin.hasNextLine()) {
Map<String, AtomicInteger> termCounts = new HashMap<>();
String s = stdin.nextLine();
String[] words = s.toLowerCase().split("[^a-zA-Z]+");
for (String word : words) {
AtomicInteger termCount = termCounts.get(word);
if (termCount == null) {
termCount = new AtomicInteger();
termCounts.put(word, termCount);
}
termCount.incrementAndGet();
}
for (Entry<String, AtomicInteger> termCount : termCounts.entrySet()) {
System.out.println("word count: " + termCount.getKey() + " " + termCount.getValue());
}
}
}
}