// 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);
};
Related
I'm attempting to fill a 2D array with the numbers 1 to 1000 and then show all the factors of those numbers. I then need to find all the prime numbers in the same array and output them. Here's what I have so far, keep in mind that I was hoping to do every step in its own method then return them but have not got that far yet
int i = 0;
//int x = 0;
String primeNumber = "";
int[] [] factorArray = new int [1000] [];
for (int x = 0 ; x < 1000 ; x++)
{
int remainder;
int y;
remainder = x % 2;
y = x / 2;
if (remainder != 0)
System.out.println (x + ": " + "1, " + x);
else if (remainder == 0)
System.out.println (x + ": " + (y) + " , " + (y / 2) + " , " + " 1, " + x);
}
for (i = 1 ; i <= 1000 ; i++)
{
int ctr = 0;
for (int x = i ; x >= 1 ; x--)
{
if (i % x == 0){
ctr = ctr + 1;
}
}
if (ctr == 2)
{
primeNumber = primeNumber + i + " ";
}
}
System.out.print ("Prime numbers from 1 - 1000 are : \n" + primeNumber);
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.");
}
I need to modify the code so that,
its structure is better
it is more readable
it uses methods and parameters
only one statement needs to be changed if a different number of integers is to be input
My new code is at the bottom but it's not working yet, can't quite figure out what else I need to do to it. If anyone could help that would be fab.
Original Code
import java.util.Scanner;
public class MakeMeBetter
{
public static void main(String[] args)
{
int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Scanner b = new Scanner(System.in);
System.out.println("Please input 10 numbers in the range 1-19 :> ");
int c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[0] = c;
int d = b.nextInt();
while (d < 1 || d > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[1] = d;
int e = b.nextInt();
while (e < 1 || e > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[2] = e;
int f = b.nextInt();
while (f < 1 || f > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[3] = f;
int g = b.nextInt();
while (g < 1 || g > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[4] = g;
int h = b.nextInt();
while (h < 1 || h > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[5] = h;
int i = b.nextInt();
while (i < 1 || i > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[6] = i;
int j = b.nextInt();
while (j < 1 || j > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[7] = j;
int k = b.nextInt();
while (k < 1 || k > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[8] = k;
int l = b.nextInt();
while (l < 1 || l > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[9] = l;
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
boolean noSwap = false;
int startAt = 0;
int stopAt = 9;
while (startAt < stopAt && noSwap == false)
{
noSwap = true;
for (int m=startAt; m<stopAt; m++)
{
if (a[m] > a[m+1])
{
int t = a[m];
a[m] = a[m+1];
a[m+1] = t;
noSwap = false;
}
}
stopAt = stopAt - 1;
}
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
double n = (a[0] + a[1] + a[2] + a[3] +
a[4] + a[5] + a[6] + a[7] +
a[8] + a[9]) / 10;
System.out.println("The minimum number is: " + a[0]);
System.out.println("The maximum number is: " + a[9]);
System.out.println("The average value is: " + n);
System.out.println("The median is: " + a[4]);
}
}
New Code
import java.util.Scanner;
import java.math.*;
public class MakeMeBetterImproved {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int array = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
int MyIntArray = array + i;
}
System.out.println("The minimum number is: " + math.min);
System.out.println("The maximum number is: " + math.max);
System.out.println("The average value is: " + math.average);
System.out.println("The median is: " + math.median);
}
}
Consider using a more dynamic structure than a primitive array.
I like ArrayLists: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Reorganize your long code into while or for loops.
An example:
ArrayList<Integer> a = new ArrayList<Integer>();
Scanner b = new Scanner(System.in);
Integer c = null;
while (a.size() != 10) {
System.out.println("Please input a number in the range 1-19 :> ");
c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
c = b.nextInt();
}
a.add(c);
}
System.out.println("\nArray contents");
for (int i=0; i<10; i++) {
System.out.print((a.get(i) < 10 ? " " : "") + a.get(i) + " ");
}
(And so on...)
Could you try this? I made a few changes.
package p2;
import java.util.Arrays;
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
sum += numbers[i];
}
Arrays.sort(numbers);
System.out.println("The minimum number is: " + numbers[0]);
System.out.println("The maximum number is: " + numbers[9]);
System.out.println("The average value is: " + sum / numbers.length);
System.out.println("The median is: " + median(numbers));
}
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
}
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");
}
import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
int[] sales;
sales = getSales();
printSales(sales);
printSummary(sales);
}
private static int[] getSales() {
Scanner input = new Scanner(System.in);
int[] temp;
System.out.print("Enter the number of salespeople: ");
temp = new int[input.nextInt()];
for (int i = 0; i < temp.length; i++) {
System.out.print("Enter sales for salesperson " +
(i + 1) + ": ");
temp[i] = input.nextInt();
}
return temp;
}
private static void printSales(int[] s) {
System.out.println();
System.out.println("Salesperson Sales");
System.out.println("----------- -----");
for (int i = 0; i < s.length; i++) {
System.out.printf("%6d%12d\n", i + 1, s[i]);
}
}
private static void printSummary(int[] s) {
int sum = 0;
int max_sale = 0; // Salesperson with the most sales
int min_sale = 0; // Salesperson with the least sales
for (int i = 0; i < s.length; i++) {
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
}
System.out.println();
System.out.println("Total sales: " + sum);
System.out.println("Average sales: " + (double)sum / s.length);
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
}
}
The purpose of the application is to take the number of salespeople as input, along with their sales and then display individual sales, total sales, and average. That is working fine, but it's also supposed to display which salesperson had the max and minimum sales and what they were (lines 51 - 54). At the moment, any time the max is greater than the number of salespeople I get an ArrayIndexOutOfBoundsException and for whatever reason can't figure it out.
1 - Modify your for loop to get the max and min without modifying the array
2 - Try to print max and min instead of printing sum[max] and some[min] (which can throws IndexOutOfBoundsException)
3 - min_sale should be greater than 0, actually a value enough large (because you can have only positive values in your array)
To summarize :
int sum = 0;
int max_sale = Integer.MIN_VALUE; // Salesperson with the most sales
int min_sale = Integer.MAX_VALUE; // Salesperson with the least sales
for (int i = 0; i < s.length; i++){
sum = (s[i] + sum);
if (s[i] > max_sale)
max_sale = s[i];
else if (s[i] < min_sale)
min_sale = s[i];
}
System.out.println("Salesperson " +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " +
" had the minimum sale with " +
min_sale);
if (s[i] > max_sale)
max_sale = s[1];
else if (s[i] > min_sale)
s[i] = min_sale;
Here you are trying to assign the value in s[1] to max_sales. whereas you should be assigning max_sale = i. and the if condition should be
if(s[i] > s[max_sale] )
Updated code:
for (int i = 0; i < s.length; i++)
{
sum = (s[i] + sum);
// Finds the index of the sales person with best sales
if (s[i] >= s[max_sale])
max_sale = i;
// If this sales person is not the best, then check if he is last
else if (s[min_sale] > s[i])
min_sale = i;
}
the specific problem that's causing your error is here,
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
s[max_sale]);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
s[min_sale]);
you're using your result as though it were an index
change it to the following
System.out.println("Salesperson " + (max_sale + 1) +
" had the maximum sale with " +
max_sale);
System.out.println("Salesperson " + (min_sale + 1) +
" had the minimum sale with " +
min_sale);