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.
Related
i would like to display 2 or more duplicated customers using joptionpane. It is working if there is only 1 duplicate customer but unfortunately the message dialogue wasnt showing if there is 2 or more duplicated customer. Here is my code.
public static void main(String[] args) {
int number;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of customers: "));
int[] one = new int[number];
int[] two = new int[number];
for (int i = 0; i < number; i++) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
int y = 0;
for (int i = 0; i < one.length - 1; i++) {
for (int w = i + 1; w < one.length; w++) {
if (one[i] == one[w]) {
two[y] = one[w];
y = y + 1;
break;
}
}
for (int p = 0; p < y - 1; p++) {
if (one[p] == two[p - 1]) {
y = y - 1;
break;
}
}
}
if (y == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else if (y != 0) {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < y; o++) {
JOptionPane.showMessageDialog(null, "Customer #" + two[o]);
//jop.showMessageDialog(null, "Duplicates: Customer #" + two[l]);
//}
}
}
}
}
How can i show the message dialogue if i want to show 2 or more duplicated customers? thank you for the help.
Break down your code into the following:
A function that takes the two lists and return a list of pairs of duplicates.
A function that takes the list of duplicates and create a string stating: "Duplicates: value1, value2..."
Show message box.
here is an solution for your problem using Collections:
public static Integer[] getDuplicates(Integer[] list) {
List<Integer> duplicates = new ArrayList<>(Arrays.asList(list));
Set<Integer> seen = new HashSet<>(Arrays.asList(list));
for (Integer i : seen) {
duplicates.remove(i);
}
Set<Integer> uniqueDuplicate = new HashSet<>(duplicates);
return uniqueDuplicate.toArray(Integer[]::new);
}
public static void main(String[] args) {
int number;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of customers: "));
Integer[] one = new Integer[number];
for (int i = 0; i < number; i++) {
one[i] = Integer.parseInt(JOptionPane.showInputDialog("Customer number: "));
}
Integer[] two = getDuplicates(one);
if (two.length == 0) {
JOptionPane.showMessageDialog(null, "\nHONEST CUSTOMERS");
} else {
JOptionPane.showMessageDialog(null, "Duplicates:");
for (int o = 0; o < two.length; o++) {
JOptionPane.showMessageDialog(null, "Customer #" + two[o]);
// jop.showMessageDialog(null, "Duplicates: Customer #" + two[l]);
// }
}
}
}
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);
}
}
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", ".");
How would I make it so that the line that says array.equals(guess) works and how would I change the load values method into not allowing duplicate numbers?
import java.util.Arrays;
import java.util.Random;
import javax.swing.JOptionPane;
public class Assignment {
private static int[ ] loadValues(){
int[] groupOfValues = new int[5];
Random randomized = new Random();
for (int index = 0; index < 5; index++) {
groupOfValues[index] = randomized.nextInt(39) + 1;
}
return groupOfValues;
}
private static void displayOutcome(int [ ] array, int guess){
if(array.equals(guess)){
JOptionPane.showMessageDialog(null, "Congrats, your guess of " + guess + " was one of these numbers:\n"
+ Arrays.toString(array));
}
else{
JOptionPane.showMessageDialog(null, "Sorry, your guess of " + guess + " was not one of these numbers:\n"
+ Arrays.toString(array));
}
}
public static void main(String[] args) {
int guessedConvert;
String guess;
do{
guess = JOptionPane.showInputDialog("Guess a number from 1-39");
guessedConvert = Integer.parseInt(guess);
}while(guessedConvert < 1 || guessedConvert > 39);
displayOutcome(loadValues(), guessedConvert);
}
}
Searching though an array requires a loop:
boolean found = false;
for (int i = 0 ; !found && i != array.length ; i++) {
found = (array[i] == guess);
}
if (found) {
...
}
To figure out if there are duplicates in loadValues add a similar code snippet inside the outer loop:
for (int index = 0; index < 5; index++) {
boolean found = false;
int next = randomized.nextInt(39) + 1;
// Insert a loop that goes through the filled in portion
...
if (found) {
index--;
continue;
}
groupOfValues[index] = next;
}