Java not inclusive of 100 in 100 Lockers - java

MY desired output is locker 1,4,9,16,36,49,81 AND 100.
I'm iterating through trying to find which lockers after a student is sent, and opens every locker. (All are closed by default) and opens every locker. then student number 2 goes to every other locker, and if it is open, close it, and if it is closed, open it. Student three does the same but with every third locker. All the way up to student 100. I know the output should be all the square numbers but I can't get the 100 to show up. What am I missing? I put a <= on both of my iterations and it doesn't work. It throws an IndexOutOfRangeException. What should I do?
import java.util.Arrays;
public class runLocker {
final static int numberOfLockers = 100;
final static int numberOfStudents = 100;
public static void main(String[] args) {
// TODO Auto-generated method stub
int LockersToCloseBy = 1;
boolean[] totalLockersArray = new boolean[numberOfLockers];
for(int i = 0; i < totalLockersArray.length - 1; i++){
totalLockersArray[i] = false;
}
for(int n= 0; n < totalLockersArray.length ; ++n){
for(int j = 0; j < totalLockersArray.length; j+=LockersToCloseBy){
if(totalLockersArray[j] == true)
{
totalLockersArray[j] = false;
}
else
{
totalLockersArray[j] = true;
}
}
LockersToCloseBy++;
}
for(int i = 0; i < numberOfLockers; i++){
if(totalLockersArray[i] == true){
System.out.println("Locker " + i + " is open");
}
}
//Currently outputs 1, 4, 9, 16, 36, 49, and 81...
//Need it to output 1,4,9,16,36,49,81,100
}
}

Your array is defined for indices [0,...,99] (100 elements total, exclusive of 100).
In the following code:
for(int i = 0; i < numberOfLockers; i++){
if(totalLockersArray[i] == true){
System.out.println("Locker " + i + " is open");
}
}
100 is not even a candidate.
An easy fix could be to set the lockers array at 101 (numberOfLockers=101), so all the loops will be inclusive of 100.

Related

Sieve of Eratosthenes will not sieve Prime Numbers

For an assignment I am doing for one of my classes, we have to implement a Sieve of Eratosthenes. I have tried seven times to get a code that works and have tried incorporating numerous solutions I've researched. I finally have one that will output numbers. Unfortunately, it prints both composite and prime numbers, and doesn't print 2.
My code is as follows:
public class EratosthenesSieveAttempt6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int limit;
System.out.print("Please enter the highest number to check "
+ "(number must be greater than 2): ");
limit = keyboard.nextInt();
while (limit <= 2){
System.out.println("Error - number must be greater than 2.");
System.out.println("Please enter the highest number to check: ");
limit = keyboard.nextInt();
}
boolean[] numbers = new boolean[limit + 1];
int newPrime = 2;
for(int i = 0; i < limit + 1; i++){
numbers[i] = true;
}
for(int j = 1; j < limit + 1; j++) {
if (j % 2 == 0) {
numbers[j] = false;
}
for(int k = j + 1; k < limit + 1; k++) {
if(numbers[k] == true){
j = k;
System.out.println(k);
}
}
}
}
}
I'm suspecting that there is a problem with my loops. I fixed the i and j variables for my first two loops so that it would print out from 2 onward, the problem seems to be that it's not marking the composite numbers as false after I've initialized the array to true.
Thank you in advance for your help.
Here's an implementation of the Sieve of Eratosthenes I wrote the other day:
import java.util.BitSet;
public static BitSet composite(int max) {
BitSet composite = new BitSet(max);
max = composite.size();
for (int i = 4; i < max; i += 2) composite.set(i, true);
for (int i = 9; i < max; i += 6) composite.set(i, true);
int p = 5;
while (p*p < max) {
if (!composite.get(p)) {
for (int i = p*p; i < max; i += p*2) composite.set(i, true);
}
p += 2;
if (p*p >= max) break;
if (!composite.get(p)) {
for (int i = p*p; i < max; i += p*2) composite.set(i, true);
}
p += 4;
}
return composite;
}
Notes:
BitSet allocates 64-bit words, so the size may be larger than you requested (for example, if you ask it to go up to 1000, it will go up to 1024; that's the reason for max = composite.size() near the top)
Gets the 2's, 3's out of the way explicitly, and then
Relies on the fact that all primes larger than 3 are congruent to either 1 or 5 mod 6; this is the reason the final loop alternates between adding 2 and 4
It returns a BitSet that tells you which numbers are composite. One way to extract just the primes from it would be:
public static int[] primes(BitSet composite) {
int size = composite.size() - 2 - composite.cardinality();
int[] primes = new int[size];
int index = 0;
for (int i = 2; i < composite.size(); i++) {
if (!composite.get(i)) primes[index++] = i;
}
return primes;
}

Coding Bubble Sort using Java

I don't know if I did this coding correctly, but can someone confirm if my doBubbleSort method and its implementation in the main method are programmed correctly? My coding requires me to create an array of size 20 and populate it with random integers between 1 and 1000 without hard coding them. The result should display the original, unsorted list of integers; and then display each pass of the bubble sorting algorithm on a separate line. I have to repeat the program until the user chooses to quit. **I have made edits to make sure that whatever variables I use, it is declared according to ArrayLists.
An example of how I want my output to come out as is shown below (although it only shows 5 integers when I'm trying to do 20):
Unsorted list: 68 3 298 290 1
Pass 1: 3 68 290 1 298
Pass 2: 3 68 1 290 298
Pass 3: 3 1 68 290 298
Pass 4: 1 3 68 290 298
// Used to capture keyboard input
import java.util.*;
// Our class called BubbleSort
public class BubbleSort {
// Create doBubbleSort method
public static void doBubbleSort(ArrayList<Integer> arr) {
boolean needNextPass = true;
while (needNextPass) {
// Array may be sorted and next pass not needed
needNextPass = false;
// Swap list
for (int i = 0; i < arr.size()-1; i++) {
if (arr.get(i) > arr.get(i+1)) {
int temp = arr.get(i);
arr.set(i, arr.get(i+1));
arr.set(i+1, temp);
printOut(i+1, arr); // using printOut method
needNextPass = true; // Next pass still needed
}
}
}
}
private static void printOut(int pass, ArrayList<Integer> list) {
System.out.print("PASS " + pass + ": ");
for (int i = 0; i < list.size()-1; i++) {
System.out.print(list.get(i) + ", ");
}
// Shows very last integer with a period
System.out.print(list.get(list.size()-1) + ".");
System.out.println();
}
// Main method
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>(); // Declare and instantiate a new ArrayList object
Scanner userChoice = new Scanner(System.in); // User input for quitting program
String choice = ""; // Will hold user choice to quit program
boolean inputFlag = false; // True if input is valid, false otherwise
// Repeat program until user chooses to quit
while (inputFlag = true) {
System.out.print("\nWould you like to continue the program? (Y/N): ");
choice = userChoice.nextLine();
if (choice.equalsIgnoreCase("Y")) {
try {
/* Create an array of size 20 and populate it with random integers between 1 and 1000.
Do not ask user for the numbers and do not hard code them */
for (int i = 0; i < 20; i++) {
int integer = (int)(1000.0 * Math.random());
array.add(integer);
}
System.out.print("\nUNSORTED LIST: ");
//Display the 20 size of the unsorted ArrayList
for (int i = 0; i < array.size() - 1; i++) {
System.out.print(array.get(i) + ", ");
}
// Shows very last integer with a period
System.out.print(array.get(array.size() - 1) + ".");
System.out.println();
doBubbleSort(array);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
}
else if (choice.equalsIgnoreCase("N")) {
break;
}
// Error message when inputting anything other than Y/N
else {
System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
System.out.println("Please try again.");
}
}
}
}
Going with your implementation, since you seem to be newly learning this, there are a few things you should change. First of all, since you're using an int array for the doBubbleSort method, use an int array in the main method as well.
The implementation of bubblesort needs to be changed too. You should first look into its logic carefully. Going through the whole array every time is not necessary.
// Create doBubbleSort method
public static void doBubbleSort(int[] arr) {
boolean needNextPass = true;
// Array may be sorted and next pass not needed
// Swap list
for (int i = 0; i < arr.length - 1; i++) {
if (needNextPass) {
needNextPass = false;
for (int j = arr.length - 1; j > i; j--) {
int temp;
if (arr[j] < arr[j - 1]) {
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
needNextPass = true; // Next pass still needed
}
}
printOut(i + 1, arr); // using printOut method
}
}
}
And then, printing the array.
private static void printOut(int pass, int[] list) {
System.out.print("PASS " + pass + ": ");
for (int i = 0; i < list.length - 1; i++) {
System.out.print(list[i] + ", ");
}
// Shows very last integer with a period
System.out.print(list[list.length - 1] + ".");
System.out.println();
}
Now the main method. I've changed the input handling part for re-running the program, and used an int array as you had originally posted.
// Main method
public static void main(String[] args) {
int[] array = new int[20]; // Declare and instantiate a new ArrayList object
Scanner userChoice = new Scanner(System.in); // User input for quitting program
boolean inputFlag = true; // True if input is valid, false otherwise
String choice;
// Repeat program until user chooses to quit
while (inputFlag == true) {
try {
/* Create an array of size 20 and populate it with random integers between 1 and 1000.
Do not ask user for the numbers and do not hard code them */
for (int i = 0; i < 20; i++) {
int integer = (int) (1000.0 * Math.random());
array[i] = integer;
}
System.out.print("\nUNSORTED LIST: ");
//Display the 20 size of the unsorted ArrayList
for (int i = 0; i < array.length - 1; i++) {
System.out.print(array[i] + ", ");
}
// Shows very last integer with a period
System.out.print(array[array.length - 1] + ".");
System.out.println();
doBubbleSort(array);
} catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
System.out.print("\nWould you like to continue the program? (Y/N): ");
choice = userChoice.nextLine();
while (!(choice.equalsIgnoreCase("Y")) && !(choice.equalsIgnoreCase("N"))) {
// Error message when inputting anything other than Y/N
System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
System.out.println("Please try again.");
choice = userChoice.nextLine();
}
if (choice.equalsIgnoreCase("N")) {
inputFlag = false;
}
}
}
}
You wrote too much boiler plate code for bubble sort. For bubble sort, use recursive method. I wrote for you simple bubble method, do what you want with output
private int[] bubbleSort(int[] arr){
int c;
boolean isArranged = false;
for (int i = 0; i < arr.length; i++) {
if (i < (arr.length - 1) && arr[i] > arr[i+1]){
c = arr[i];
arr[i] = arr[i+1];
arr[i+1] = c;
isArranged = true;
}
}
if (isArranged){
return bubbleSort(arr);
}else{
return arr;
}
}
Call this like:
Scanner in = new Scanner(System.in);
int length = in.nextInt();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = in.nextInt();
}
Main main = new Main();
int[] newArr = main.bubbleSort(arr);
for (int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i] + " ");
}
You can write ArrayList instead int array.

finding first even element and outputting index

My program:
public static void evenval (int[] array ){
int even=0;
for (int r = 0; r < array.length; r++) {
while (r == array[r]) {
if (array[r] % 2 ==0) {
even = array[r];
System.out.println("The first even number's index is:"+array[r]);
}
I'm trying to make a loop where it finds the first even number in an array and get it to output it's index to the main method.
I'm stuck, please help.
Try to use just for loop like this:
int even = 0;
for (int r=0;r<array.length;r++){
if (array[r] % 2 ==0){
even = r;
break;
}
}
System.out.println("The first even number's index is:"+ even );
Using the break; when find the even number.
For example if you want to find 100th even number use this:
int even = 0;
int count = 0;
for (int r=0;r<array.length;r++){
if(array[r] % 2 ==0){
if(count !=100){
count++;
}else{
even = r;
break;
}
}
}
System.out.println("The first even number's index is:"+ even );
It's better to create a small method in your class and call it from main to do this for you and return the index or -1 if a valid even number is not found. :
public class EvenTest{
int getFirstEvenIndex(int[] array){
for (int r=0; r < array.length; r++){
if (array[r] % 2 ==0){
return r;
}
}
return -1;
}
public static void main(String... args){
int[] arr = [3,5,1,2,7,8];
EvenTest et = new EvenTest();
System.out.println("First even is at index: " + et.getFirstEvenIndex(arr));
}
}
class test {
public static void main(String[] args) {
int[] array = {5, 7, 1, 8, 9, 3,110};
int evenCount =2;//required count ....for 100th even put evenCount = 100;
evenval(array,evenCount);
}
public static void evenval(int[] array,int evenCount) {
for (int i=0;i<array.length;i++) {
if(array[i] % 2 == 0&&--evenCount==0) {
System.out.println("the required even number is "+array[i]+" at index "+i);
return;
}
}
}
}
Just remove while statement in your code.
int even = 0;
for (int r = 0; r < array.length; r++) {
if (array[r] % 2 == 0) {
even = array[r];
System.out.println("The first even number's index is:" + array[r]);
}
}
If you want to stop after finding first even number, just put break inside if statement
int even = 0;
for (int r = 0; r < array.length; r++) {
if (array[r] % 2 == 0) {
even = array[r];
System.out.println("The first even number's index is:" + array[r]);
break;
}
}
You could simply use a bitwise operation as well (performance wise, it's quicker):
for (int n : array) {
if ((n&1) == 0) {
System.out.println("The first even number's index is:" + n);
break;
}
}

java fill 2D array with specific method

I have an 2D array(matrix) and a Integer n.n is full square
for example if n equals 16 fill matrix like this.
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
what can I do?
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the dimension of the matrix : ");
int dimension = Integer.parseInt(br.readLine());
System.out.print("Enter the number of elements : ");
int n = Integer.parseInt(br.readLine()); // total number of elements to be filled
n = n/dimension; // Get the number of rows and columns
if(n % dimension != 0){
// Not a Square matrix
}
int circularArray[][] = new int[n][n];
int k = 1, c1 = 0, c2 = n - 1, r1 = 0, r2 = n - 1;
while (k <= n * n) {
for (int i = c1; i <= c2; i++) {
circularArray[r1][i] = k++;
}
for (int j = r1 + 1; j <= r2; j++) {
circularArray[j][c2] = k++;
}
for (int i = c2 - 1; i >= c1; i--) {
circularArray[r2][i] = k++;
}
for (int j = r2 - 1; j >= r1 + 1; j--) {
circularArray[j][c1] = k++;
}
c1++;
c2--;
r1++;
r2--;
}
/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(circularArray[i][j] + "\t");
}
System.out.println();
}
}
Here is a tiny example how this could look like.
What is actually happening is written as comments.
public class TestArray {
// A simple enum for each direction
public enum Mode {
right, down, left, up;
}
public static void main(String[] args) {
final int size = 4; // We set a fixed size for the square
int[][] arr = new int[size][size]; // create the array from the size
// Running vallues
// i and j to refer to the array.
// val holds the current value to be inserted
// circle holds how often we are going up. Each time we go up it´s increased by one
// In the end this should reduce the amount of steps we do to not override
// already assigned values.
int i = 0,j = 0, val = 1, circle = 0;
Mode runningMode = Mode.right; // We start by going to the right.
while(size*size >= val) { // loop until we reached the last value
arr[j][i] = val++; // Assign the value and increase the value by one afterwards.
// We go right.
if(runningMode == Mode.right) {
// we reached the last assignable item.
// subtract one to not get an index out of bound,
// subract the variable trips that is used to get the last item for the inner circle
if(i==arr.length-1-circle) {
// We are going down now and increase j
runningMode = Mode.down;
++j;
} else {
// go on going right.
++i;
}
} else if(runningMode == Mode.down){
// we reached the last assignable item.
// subtract one to not get an index out of bound,
// subract the variable trips that is used to get the last item for the inner circle
if(j==arr.length-1-circle) {
// We are going left now and decrease i
runningMode = Mode.left;
--i;
} else {
// go on going down.
++j;
}
} else if(runningMode == Mode.left){
// we reached the last assignable item.
// add the variable trips that is used to get the last item for the inner circle
if(i==0+circle) {
// We are going up now and decrease j
// Simultaniosly we are about to end our next circle, so we increase circle
runningMode = Mode.up;
++circle;
--j;
} else {
// go on going left.
--i;
}
} else if(runningMode == Mode.up){
// we reached the last assignable item.
// add the variable trips that is used to get the last item for the inner circle
if(j==0+circle) {
// We are going right now and increase i
runningMode = Mode.right;
++i;
} else {
// go on going up.
--j;
}
}
}
// Print the result
for(int[] a : arr) {
for(int b : a) {
System.out.print(b + "\t" );
}
System.out.println();
}
}
}

Arraylist, incomparable types: DieClass and int

Trying to write a program that "rolls" dice and displays the results of the players and computer's rolls, as well as find how many of each number was rolled. Say, player rolls 3 4 3 5 6, then the player has a match composed of 2 3's. Haven't wrote the code to display the matching yet.
My problem is that I am trying to record the rolls to an ArrayList, then compare each number for the players and computers rolls from the ArrayList, and count up the number of each number's occurrence, but it I keep getting the error of
error: incomparable types: DieClass and int
Whenever I try to compare from the ArrayList
The program in question uses methods from the class DieClass
import java.util.ArrayList;
public class DieTester
{
private static ArrayList<DieClass> player = new ArrayList<DieClass>();
private static ArrayList<DieClass> computer = new ArrayList<DieClass>();
public static void main(String[] args)
{
for(int a = 1; a <= 5; a++)
{
DieClass roller = new DieClass();
player.add(roller);
}
for(int a = 1; a <= 5; a++)
{
DieClass roller = new DieClass();
computer.add(roller);
}
System.out.println("The user rolls: "+player);
System.out.println("The computer rolls: "+computer);
}
public String findMatching()
{
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
for(int i=1; i<player.size(); i++)
{
if(player.get(i)==1)
{
count1++;
}
else if(player.get(i)==2)
{
count2++;
}
else if(player.get(i)==3)
{
count3++;
}
else if(player.get(i)==4)
{
count4++;
}
else if(player.get(i)==5)
{
count5++;
}
}
for(int i=1; i<player.size(); i++)
{
if(computer.get(i)==1)
{
count1++;
}
else if(computer.get(i)==2)
{
count2++;
}
else if(computer.get(i)==3)
{
count3++;
}
else if(computer.get(i)==4)
{
count4++;
}
else if(computer.get(i)==5)
{
count5++;
}
}
}
}
Your problem is that you are comparing DieClass with Integers
if(player.get(i)==1)
For the counters, why don't you use an array of int? like
int counters [] = new int[6];
counters[2]++;
Please post DieClass, however, I think that your code should be like this.
for (DieClass dieClass : player) {
counters[dieClass.getNumber()-1]++; //Supose that DieClass has a getNumber method and set minus one because counters goes from 0 to 5
}

Categories

Resources