My code has to print it one time but doesn't - java

Okey I wrote a code to tell me the occurrence of numbers in my array. It does its job but prints it occurrence times. BTW I can't use any of collection, hashmap etc. Only loops.
int[] Bag = new int[0];
boolean isit = true;
do{
String name = scanner.next();
int[] NewBag;
if (name.equals("A")){
int num = scanner.nextInt();
NewBag = new int[Bag.length + 1];
NewBag[NewBag.length - 1] = num;
for(int i = 0; i < Bag.length; i++){
NewBag[i] = Bag[i];}
Bag = NewBag;
System.out.println(num + " added to Bag.");}
else if (name.equals("L")){
for(int m = 0; m < Bag.length; m++)
{
int occurrence = 0;
for(int n = 0 ; n < Bag.length ; n++)
{
if(Bag[m] == Bag[n])
{
occurrence++;
}
}
if(occurrence > 1)
{
System.out.println(Bag[m] + " occurs " + occurrence + " times");
}
else
{
System.out.println(Bag[m] + " occurs " + occurrence + " time");
}
}while ( isit == true );
For example, if my array is {5,6,6,7};
Output:
5 occurs 1 time
6 occurs 2 times
6 occurs 2 times
7 occurs 1 time
It has to write "6 occurs 2 times" one time.
I know the solution is easy to find but i really can't see how to solve this. Thank you.

Here is what is going on.
Your array contains: [5, 6, 6, 7]
You are going step by step printing "X occurs Y times" once per array element. Because the array contains two 6 element, you end up printing the output twice. One way to correct this problem is to do this:
for (int m = 0; m < Bag.length; m++) {
boolean Seen = false;
for (int n = 0 ; n < m - 1 ; n++) {
if (Bag[m] == Bag[n]) {
Seen = true;
break;
}
}
if (Seen) {
continue;
}
int occurrence = 0;
for (int n = 0 ; n < Bag.length ; n++) {
if (Bag[m] == Bag[n]) {
occurrence++;
}
}
if (occurrence > 1) {
System.out.println(Bag[m] + " occurs " + occurrence + " times");
} else {
System.out.println(Bag[m] + " occurs " + occurrence + " time");
}
}
The first time around you run into 6 it'll get added into Seen. The second time around, it'll already be inside Seen so the print statement will be skipped.

Does the following work? It skips the number of occurrences.
for(int m = 0; m < Bag.length; m++){
int occurrence = 0;
for(int n = 0 ; n < Bag.length ; n++){
if(Bag[m] == Bag[n]){
occurrence++;
}
}
if(occurrence > 1){
System.out.println(Bag[m] + " occurs " + occurrence + " times");
m+=occurrence-1;
}
else{
System.out.println(Bag[m] + " occurs " + occurrence + " time");
}

Related

Count each character

I'm trying to count each char in string for example:
Sample input: abababx
Sample output :
a appears 3 times
b appears 3 times
x appears 1 time
Here is what I've done :
String s = input.nextLine();
//Invoke the count method to count each letter
int[] counts = countLetters(s.toLowerCase());
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println((char)('a' - i) + " appears " +
counts[i] + ((counts[i] == 1 ? " time" : " times")));
}
private static int[] countLetters(String s) {
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
I'm getting:
a appears 3 times
` appears 3 times
J appears 1 time

How to break out of a while loop in java?

// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
while (list.size() != 0) {
for (int j = 1; j < list.size(); j++)
{
//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
break;
}
}
}
}
list.remove(0);
};
Output:
1 and 2 and size is 4
Counter is 2
1 and 3 and size is 4
Counter is 3
1 and 4 and size is 4
Counter is 4
here 4
2 and 3 and size is 3
Counter is 5
3 and 4 and size is 2
Counter is 6
here 6
Ideally, i want it to stop when Counter is 4 and don't go on to execute "2 and 3 and size is 3 "
Much appreciated!
You need to use a label for the loop . Please try below snippet :
// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
outerwhileloop:
while (list.size() != 0) {
for (int j = 1; j < list.size(); j++)
{
//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
break outerwhileloop;
}
}
}
}
list.remove(0);
};
Just move the code to a method and call return. Or else, you can use something called labeled break.
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
You can use java label for that as:
int x = 1;
outerLoopLabel:
while(x != 10) {
int fact = 0;
for(int i=0;i <=x; i++) {
fact +=i;
if(fact > 25) {
break outerLoopLabel;
}
}
System.out.println("Number: "+ x + " and fact: " + fact);
++x;
}
Output without label :
Number: 1 and fact: 1
Number: 2 and fact: 3
Number: 3 and fact: 6
Number: 4 and fact: 10
Number: 5 and fact: 15
Number: 6 and fact: 21
Number: 7 and fact: 28
Number: 8 and fact: 36
Number: 9 and fact: 45
Output with label:
Number: 1 and fact: 1
Number: 2 and fact: 3
Number: 3 and fact: 6
Number: 4 and fact: 10
Number: 5 and fact: 15
Number: 6 and fact: 21
You can add a boolean variable like this:
// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
boolean isBreak = false;
while (list.size() != 0 && !isBreak) {
for (int j = 1; j < list.size(); j++)
{
//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
isBreak = true;
break;
}
}
}
}
list.remove(0);
};

Math.random won't randomize number 9 whenever it has to be assigned to last array slot

My code creates an array of size 10, it randoms numbers from 0 to 9 to fit in each slot. The problem comes when the number 9 is not picked until the last space. Math.random keeps randomizing numbers but it will never pick the number 9. I ran the program for about 1 minute and it never picked it.
Here is my program
public class GenerateRandomNumbers{
// main method
public static void main(String[] args) {
int aSize = 10;
int[] a = new int[aSize];//setting size of array
for(int i = 0; a.length > i; i++){//looping through the whole array
a[i] = (int)(Math.random()*9) + 1;//assigning random number to each slot of array
System.out.println("assign " + a[i] + " to i" + i);
//looping through filled array slots.
for(int k = i-1; -1 < k; k--){
System.out.println("Check if " + a[i] + " i"+ i + " = " + a[k]+ " k"+ k );
//if not unique give a new number
if(a[i] == a[k]){
System.out.println("CHANGE HERE");
a[i] = (int)(Math.random()*9) + 0;
System.out.println("assign " + a[i] + " to " + i);
k = i;//reset loop so it checks all over again
}
}
System.out.println("ACCEPT");
}
for(int i = 0; a.length > i; i++){
System.out.println(a[i]);
}
}
}
Can someone explain me what is causing the bug?
Your line a[i] = (int)(Math.random()*9) + 0; is different from the time you used Math.random() above. Above you said (int)(Math.random()*9) + 1, that will give you a random number in the range of [1,9].
(int)(Math.random()*9) + 0 will never evaluate to 9, its range is [0,8].

How to return a single print statement from a search() method in an array?

I'm having trouble with my search method. What I want to do is have my search method print the statement only once. So if my array contains "3" more than once, I only want to print "3 was found." once instead of checking each value and reporting that there is or is not a "3" at that point in the array. How would I do that?
To clarify, this is what I have:
`0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was not found.
3 was found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was not found.
2 was found.
2 was not found.
2 was not found.`
And this is what I want:
0,0,0,0,0,0,0,0,0,0
4,9,6,9,0,8,5,2,8,3
Average Value: 5.4
Maximum Value: 9
Minimum Value: 0
3 was found.
2 was not found.
So this is my complete class. I created a method called initialize that will assign each element in my array a random integer between 0 and 10; a method called print to print out the contents of my array; a method called printStats to find and then print the average, maximum, and minimum value in my array; and a method called search that searches my array (and prints the result) for an integer parameter passed to my method.
Everything works correctly.
public class ArrayLab
{
private int[] array;
public ArrayLab(int numElements)
{
array = new int[numElements];
}
public void initialize()
{
array[0] = (int) (Math.random()*11);
array[1] = (int) (Math.random()*11);
array[2] = (int) (Math.random()*11);
array[3] = (int) (Math.random()*11);
array[4] = (int) (Math.random()*11);
array[5] = (int) (Math.random()*11);
array[6] = (int) (Math.random()*11);
array[7] = (int) (Math.random()*11);
array[8] = (int) (Math.random()*11);
array[9] = (int) (Math.random()*11);
}
public void print() {
System.out.println(array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "," + array[4] + "," + array[5] + "," + array[6] + "," + array[7] + "," + array[8] + "," + array[9]);
System.out.println();
}
public void printStats()
{
double sum = 0;
int max = 0;
int min = 0;
min = array[0];
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
if (array[i] > max)
{
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
double average = sum/array.length;
System.out.println("Average Value: " + average);
System.out.println("Maximum Value: " + max);
System.out.println("Minimum Value: " + min);
}
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
}
else
{
System.out.println(numChosen + " was not found.");
}
}
}
}
Start using return or break statement to break the loop after you hit the first successful search.
Also, you should not print the Was Not Found every time while iterating the array. You should print it only once in the end when your array gets exhausted completely and search query is not found.
Here is the modified code snippet:
boolean flag = false;
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
flag = true;
break;
}
}
if(!flag) {
System.out.println(numChosen + " was not found.");
}
Alternatively, you can also do the following:
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
Well, you don't need to keep iterating through the loop once you found the number. Also, you want to print "was not found" in a case it didn't find anything, meaning the loop finished without printing anything yet.
So this is how you should implement it:
public void search(int numChosen)
{
for(int i = 0; i < array.length; i++)
{
if(array[i] == numChosen)
{
System.out.println(numChosen + " was found.");
return;
}
}
System.out.println(numChosen + " was not found.");
}
In a case it found something, it will print the message and exit the method and never reach the printing of second message. It will only print the second message when the loop is over.
You are displaying results in your public void search(int numChosen) function. In your case, instead of printing every time you encounter a match, put a counter instead, then print once: that counter with the rest of you sentence.
Try this:
public void search(int numChosen)
{
int count = 0;
for (int i = 0; i < array.length; i++)
if (array[i] == numChosen)
count++;
if (count == 0)
System.out.println(numChosen + " was not found.");
else
System.out.println(numChosen + " was found " + count + " times.");
}

How to compare the given integer with possible roots

I could not name the question in the best way... My aim is to write a program that takes integer n from user. Then compare with the third power of two integers a and b.
If a^3 + b^3 is smaller than or equal to the given input, I want to print out every single possible calculation to the user.
My code is as follows:
System.out.println("Hi. Please insert an integer: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double root = Math.cbrt(n);
int rootInt = (int) root;
for (int i = 0; i < rootInt; i++){
for (int j = 0; j < rootInt; j++){
if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){
double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
int totalInt = (int) t;
System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );
} else {
}
j++;
}
i++;
}
When I run this and give an input as 30, it prints
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16
What am I doing wrong?
You increase j and i twice. That's why you test only the even values for i, j.
If you want to correct the code, remove the i++, j++ from the end and use only the increments from the 2 fors.

Categories