Array count logic error - java

Made some edits to the code to try and figure out why my X's [-1] are not being included in finding my average for that row. That is throwing of my averages. Any idea why It is not counting my -1's?
output[expected]:
USER INPUT: 3
O O O
X X X
X X X
TOTAL OPENNESS OF [I][J] = 1
TOTAL OPENNESS OF [I][J+1] = 2
TOTAL OPENNESS OF [I][J+2] = 1
TOTAL SUM AVERAGE FOR THAT ROW = 1.3
HOWEVER..FOR ROW 2 AND ROW 3
TOTAL SUM AVERAGE FOR THOSE ROWS = 0
WHICH IS INCORRECT IT SHOULD = -1
public static void openfactor(char[][] mazeValue, int n){
for(int i = 1; i<=n; i++)
{
double rowAvg=0;
double totalRowAvg=0;
for(int j=1;j<=n;j++)
{
int count=0;
int totalOpeness=0;
int totalRowOpeness = 0;
//double rowAvg=0;
if(mazeValue[i][j]=='X'){
System.out.println("tHIS IS AN X FOR : [" + i + "]" +"[" + j + "] IS -1 ");
count = -1;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=1)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1 && j-1>=1)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n && i+1<=n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<=n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=1 && i+1<=n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=1 && j+1<=n)
{
if(mazeValue[i-1][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " +totalOpeness);
totalRowOpeness = totalRowOpeness + totalOpeness;
//}//eND OF iF CONDITION\
}
rowAvg = (double)totalRowOpeness/(double)n;
System.out.println("ROW AVERAGE: "+rowAvg);
totalRowAvg = totalRowAvg + rowAvg;
System.out.println("SUM ROW AVERAGE: "+totalRowAvg);
}
System.out.println("TOTAL SUM ROW AVERAGE: " +totalRowAvg);
}
}
public static void printMaze(char mazeValue[][]) {
System.out.println("MAZE");
for (int i = 1; i < mazeValue.length; i++) {
for (int j = 1; j < mazeValue[i].length; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n + 1][n + 1];
System.out.println("ENTER A PATH: ");
for (int i = 0; i < mazeValue.length; i++) {
for (int j = 0; j < mazeValue[i].length; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
mazeValue[i][j] = 'X';
else {
mazeValue[i][j] = kbd.next().charAt(0);
}
}
}
printMaze(mazeValue);
horizontalPath(mazeValue, n);
System.out.println(" ");
verticalPath(mazeValue,n);
System.out.println(" ");
openfactor(mazeValue, n);
}
}

I do not completely understand what u want to accomplished but I am going to to assume you want to find repeated values, do this using some search algorithm below is an example of a binary search. Hope it helps.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}

Here's the complete code for your request. you need to reorder your if statements a little bit your logic was right:
and here is the output :
MAZE
O O X
O O O
X X O
TOTAL OPENESS FOR : [0][0] IS 3
TOTAL OPENESS FOR : [0][1] IS 4
THERE IS AN X HERE FOR : [0][2]
Average of O's in this row is : 66.66667%
TOTAL OPENESS FOR : [1][0] IS 3
TOTAL OPENESS FOR : [1][1] IS 5
TOTAL OPENESS FOR : [1][2] IS 3
Average of O's in this row is : 100.0%
THERE IS AN X HERE FOR : [2][0]
THERE IS AN X HERE FOR : [2][1]
TOTAL OPENESS FOR : [2][2] IS 2
Average of O's in this row is : 33.333336%
here's the code:
import java.util.Scanner;
public class sof {
public static boolean IsOutOfBound(int i, int j, int n)
{
if (i-1<1 || j-1<1 || i+1>n || j+1>n)
return true;
else
return false;
}
public static void openfactor(char[][] mazeValue, int n)
{
for(int i = 0; i<n; i++)
{
int TotalCounts=0;
for(int j=0;j<n;j++)
{
int count=0;
if(mazeValue[i][j]=='X'){
System.out.println("THERE IS AN X HERE FOR : [" + i + "]" +"[" + j + "] ");
//TotalCounts--;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=0)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0 && j-1>=0)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n && i+1<n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=0 && i+1<n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=0 && j+1<n)
{
if(mazeValue[j+1][i-1]=='O')
count++;
}
// System.out.println("cout: "+count);
//totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " + count);
TotalCounts++;
}//END OF else CONDITION
}//End of J loop
float Average = ((float)TotalCounts/(float)n) * 100;
System.out.println("Average of O's in this row is : " + Average+ "%");
}//End of I loop
}
public static void printMaze(char mazeValue[][],int n) {
System.out.println("MAZE");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for (int i = 0; i <n; i++) {
for (int j = 0; j < n; j++) {
//if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
// mazeValue[i][j] = 'X';
// else {
mazeValue[i][j] = kbd.next().charAt(0);
// }
}
}
printMaze(mazeValue,n);
openfactor(mazeValue, n);
}
}

Related

Java Single Dimensional Arrays

Enter the integers between 1 and 50: 1 2 1 0
1 occurs 2 times
2 occurs 1 times
1 occurs 2 times
How can I do to get 1 occurs only 1 times ?
The problems is to it's print many times.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
Edit this Code
Try this (Refer to code comments for explanations):
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
while (i < 100) { // Check if the array is already full
System.out.print("Enter 0 to Exit or enter the integers between 1 and 50 (Input #" + (i + 1) + ") : ");
int value = input.nextInt();
if (value == 0) {
break;
}
if (value < 1 || value > 50) { // check if input is between 1 and 50
System.out.println("Input is not between 1 and 50");
} else {
num[i] = value;
System.out.println();
}
i++;
}
System.out.println();
System.out.println("Result: ");
for (int j = 0; j < i; j++) {
int n = 0;
boolean isAlreadyPrinted = false; // flag to check if will be printed or not
for (int k = 0; k < i; k++) {
if (num[j] == num[k]) {
if (j > k) { // this means that the same value is already found and printed
isAlreadyPrinted = true;
}
n++;
}
}
if (!isAlreadyPrinted) {
System.out.println(num[j] + " occurs " + n + " times");
}
}
}
}
The problem is with your for loop.
You should not run the j's value up to i. That's why "1 occurs 2 times" is printing twice. What you have to do is checking the value of the array's certain index has been occurred multiple times before print part executed.
public static<T> T[] subArray(T[] array, int beg, int end) {
return Arrays.copyOfRange(array, beg, end + 1);
}
public static boolean hasDuplicateValues (int[] array, int value )
{
boolean result = false ;
int count = 0 ;
for (int i=0 ; i< array.length; i++)
{
if(array[i] == value)
{
count = count+1 ;
}
}
if(count > 1)
{
result = true;
}
return result;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int i = 0;
System.out.print("Enter the integers between 1 and 50: ");
num[i] = input.nextInt();
while(num[i] != 0){
i++;
num[i] = input.nextInt();
}
for(int j=0;j<i;j++){
int n = 0;
for(int k=0;k<i;k++){
if(num[j] == num[k]){
n++;
}
}
int[] subarray = subArray(num, 0, i);
boolean isDuplicate = hasDuplicateValues (subarray , num[i] )
if(isDuplicate == false )
{
System.out.println(num[j] + " occurs " + n + " times");
}
}
}

Correctly Printing For Loops in Java

I have been working on this program for a few hours and the code is working correctly but I can't seem to get it to print out correctly, it should just be printing once for each value, such as:
number: 6
dividers: 2 3 6 1
prime: is not prime
Output
Can anyone help? Screenshot is attached. Thanks!
public static void main(String[] args) {
Random randomNums = new Random();
int count;
for (int i = 1; i <= 37; i++) {
count = randomNums.nextInt(100) + 1;
System.out.println("number " + count);
for (int b = 1; b<=count; b++) {
if (count % b == 0) {
System.out.println("dividers " + b);
}
}
for (int a = 2; a< count; a++) {
if (count % a == 0) {
System.out.println("is not prime");
}
if (count % a != 0) {
System.out.println("is prime");
}
}
}
}
}
try to write this code :
public static void main(String[] args) {
Random randomNums = new Random();
int count;
for (int i = 1; i <= 37; i++) {
count = randomNums.nextInt(100) + 1;
System.out.println("number " + count);
String dividers = "";
for (int b = 1; b<=count; b++) {
if (count % b == 0) {
dividers += b.toString() +" ";
}
}
// control the print beside loop
System.out.println("dividers " + dividers);
// add the control for whether prime
bool prime = true;
for (int a = 2; a< count; a++) {
if (count % a == 0) {
System.out.println("prime : is not prime");
// add the control for skip loop
prime = false;
break;
}
}
if(prime){
System.out.println("prime : is prime");
}
}
}
}
based upon your logic, I am guessing that if you decide that a number is not a prime then that is the final result,
so
boolean isPrime = true;
String dividers = "";
for (int a = 2; a< count; a++) {
if (count % a == 0) {
isPrime = false;
dividers += a+" ";
}
}
if (isPrime) {
System.out.println ("is Prime");
} else {
System.out.println ("dividers "+dividers);
System.out.println ("is not Prime");
}

Role 2 dice 100000 times, write the amount of times each sums and rolled and make a graph - Java

Here is my code so far
package chapter3Codes;
public class TwoDice {
public static void main(String[] args) {
Dice a = new Dice();
Dice b = new Dice();
int sum = 0;
int is2=0; int is3=0; int is4=0; int is5=0; int is6=0;
int is7=0; int is8=0; int is9=0; int is10=0; int is11=0; int is12=0;
for (int i=1; i<= 100000; i++){
a.roll();
a.getFaceValue();
b.roll();
b.getFaceValue();
sum = (a.getFaceValue()+ b.getFaceValue());
if(sum == 2){
is2++;
}else{
if(sum == 3){
is3++;
}else{
if(sum == 4){
is4++;
}else{
if(sum == 5){
is5++;
}else{
if(sum == 6){
is6++;
}else{
if(sum == 7){
is7++;
}else{
if(sum == 8){
is8++;
}else{
if(sum == 9){
is9++;
}else{
if(sum == 10){
is10++;
}else{
if(sum == 11){
is11++;
}else{
if(sum == 12){
is12++;
}
}
}
}
}
}
}
}
}
}
}
}
System.out.println("The sum is 2 "+ is2 + " many times");
System.out.println("The sum is 3 "+ is3 + " many times");
System.out.println("The sum is 4 "+ is4 + " many times");
System.out.println("The sum is 5 "+ is5 + " many times");
System.out.println("The sum is 6 "+ is6 + " many times");
System.out.println("The sum is 7 "+ is7 + " many times");
System.out.println("The sum is 8 "+ is8 + " many times");
System.out.println("The sum is 9 "+ is9 + " many times");
System.out.println("The sum is 10 "+ is10 + " many times");
System.out.println("The sum is 11 "+ is11 + " many times");
System.out.println("The sum is 12 "+ is12 + " many times");
for(int i = 0; i <= is2;i++){
System.out.println("*");
}
for(int i = 0; i <= is3;i++){
System.out.println("*");
}
for(int i = 0; i <= is4;i++){
System.out.println("*");
}
for(int i = 0; i <= is6;i++){
System.out.println("*");
}
for(int i = 0; i <= is7;i++){
System.out.println("*");
}
for(int i = 0; i <= is8;i++){
System.out.println("*");
}
for(int i = 0; i <= is9;i++){
System.out.println("*");
}
for(int i = 0; i <= is10;i++){
System.out.println("*");
}
for(int i = 0; i <= is11;i++){
System.out.println("*");
}
for(int i = 0; i <= is12;i++){
System.out.println("*");
}
}
}
How do I fix my code so that every time is2 is incremented a star prints.
For example if is2 was incremented 3 times and is3 was incremented 4 times it would show like this
***
****
Since you haven't learned arrays yet, I'll just show you how to print the *s for your twos on one line. You need System.out.print many times, but only one System.out.println to finish the line. Something like,
for(int i = 0; i <= is2;i++){
System.out.print("*"); // <-- on one line.
}
System.out.println(); // <-- end the line.
If you use a hashmap things can be compacted too much as below:
public class TwoDice {
public static void main(String[] args) {
Dice a = new Dice();
Dice b = new Dice();
Map<Integer,Integer> sumMap = new Hashmap<Integer,Integer>();
int sum = 0;
for (int i=1; i<= 100000; i++){
a.roll();
a.getFaceValue();
b.roll();
b.getFaceValue();
//
sum = (a.getFaceValue()+
b.getFaceValue());
if(sumMap.get(sum)==null){
sumMap.put(sum,1);
}else{
sumMap.put(sum,sumMap.get(sum)+1);
}
}
for(int i=1; i<=12; i++)
{
int size = sumMap.get(i)==null? 0 : sumMap.get(i);
System.out.println("The sum is "+i+" "+ size +
" many times");
}
for(int i=1; i<=12; i++)
{
int size = sumMap.get(i)==null? 0 : sumMap.get(i);
for(int j=1; j<=size; j++){
System.out.print("*");
}
System.out.println("");
}
}
}

How to make a newline for every 15 spaces with numbers in java

I have the following code that finds the prime factors from 1 to the user input. The problem is that the output is in one very long line, I want every 15 numbers to output then go to the next line. How would I do that?
Here is my code:
public static void main (String args[])
{
System.out.println("\nLab1la\n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the primes upperbond ==>> ");
final int MAX = input.nextInt();
input.nextLine();
boolean primes[];
primes = new boolean[MAX];
ArrayList<Integer>PrimeFactor = new ArrayList<Integer>();
for (int i = 2; i < MAX + 1 ; i++)
{
PrimeFactor.add(i);
}
System.out.println("COMPUTING RIME NUMBERS");
System.out.println();
System.out.println("PRIMES BETWEEN 1 AND " + MAX);
CompositeNumbers(PrimeFactor);
for (int value : PrimeFactor)
{
System.out.print(value);
System.out.print(" ");
}
}
public static void CompositeNumbers(ArrayList<Integer> PrimeFactor)
{
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (!isPrime(PrimeFactor.get(i)))
{
PrimeFactor.remove(i);
i--;
}
}
}
public static boolean isPrime(int n)
{
if(n==1)
{
return true;
}
for (int i = 2; i < n +1/2; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}
You could do something like this:
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (i > 0 && i % 15 == 0) System.out.println();
System.out.print(PrimeFactor.get(i));
System.out.print(" ");
}
You could just have a counter and take a mod of this counter value for 15 and print it in the next line, like below. Like #soong described
int counter = 0;
for (int value : PrimeFactor)
{
if(counter % 15 == 0){
System.out.println();
}
System.out.print(value);
System.out.print(" ");
counter++;
}

How can I output several numbers per line in java

Hi I am new in programming,so please don't laugh from my stupid question.
I wrote program which ask user for input a number than program should output all the numbers from 0 to that entered number(doesn't matter if it is positive or negative).
I have tried 3 different versions
Here is my code:
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
int num = PutiL.validNum(min, max, "number");
//this my utility methode which check if number is in range and if it is not a double or letter
int i = 0, z;
int y = 0;
//3rd version
while (i <= num) {
for (z = 0; z < 4; z++) {
System.out.print(i + " ");
i++;
}
System.out.println();
}
//2nd version
if (num > 0) {
for (i = 0; i <= num; y++) {
for (z = 0; z < 4; z++) {
System.out.print(i + ",");
i++;
}
System.out.println();
}
} else {
for (i = 0; i > num; y--) {
for (z = 0; z < 4; z++) {
System.out.print(i + ",");
i--;
}
System.out.println();
}
}
//1st version`enter code here`
if (num > 0) {
for (i = 0; i <= num; i++)
{
System.out.print(i + ",");
}
} else {
for (i = 0; i >= num; i--) {
System.out.print(i + ",");
}
}
System.out.println();
Problem is that code doesn't stop straight after number typed in by user. Will someone give me a hint what is wrong as I don't have any more ideas.
And here is the PutiL methode
public static int validNum(int min, int max, String words) {
int num;
do {
System.out.println("Please enter " + words);
while (!kb.hasNextInt()) {
System.out.println("Please re-enter ");
kb.nextLine();
}
num = kb.nextInt();
if (num < min || num > max) {
System.out.println("Not in range - re-enter\tproper range is "
+ min + " - " + max);
}
} while (num < min || num > max);
return num;
}
//2nd version
if (num > 0)
{
for (i = 0; i <= num; y++) <== THIS MAKE INFINITE too, OKAY.. ^^, change i to stop
{
for (z = 0; z < 4; z++)
{
System.out.print(i + ",");
i++;
}
System.out.println();
}
} else
{
for (i = 0; i > num; y--) <== THIS MAKE INFINITE LOOPS, OKAY.. ^^, it must i to stop
{
for (z = 0; z < 4; z++)
{
System.out.print(i + ",");
i--;
}
System.out.println();
}
}
don't forget to accepted the answer if it goes right.. ^^
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
if (number >= 0) {
for (int i = 0; i <= number; i++) {
System.out.println(i);
}
} else {
for (int i = 0; i >= number; i--) {
System.out.println(i);
}
}
}
Or a bit more concise and with duplicating the println statement...
public static void main(String[] args) {
int number = Integer.parseInt(args[0]);
int increment = number >= 0 ? 1 : -1;
for (int i = 0; i != number + increment; i += increment) {
System.out.println(i);
}
}
This will give the user a dialog and the value the user enters will count to zero.
First import:
import javax.swing.JOptionPane.*;
Then:
int user_choice = Integer.parseInt(
showInputDialog(null, "Please enter a number."));
if(user_choice > 0){
for(int temp = 0; temp <= user_choice; temp++){
System.out.println(temp);
}
}
else{
for(int temp = 0; temp >= user_choice; temp--){
System.out.println(temp);
}
}
"program should output all the numbers from 0 to that entered number"
and
"I want them print for example 4 in a one line and than skip to another line"
if(num >=0) {
for (z = 0; z <= num; z++)
{
System.out.print(z + " ");
if(z > 0 && z%4==0)
System.out.println();
}
}
else {
// similar loop for negatives
}
System.out.println();
Thank you all for help I solve it my self was really easy here is code I useit and now its work perfectly
for(i = 0; i <= num; i++)
{
System.out.print(i + " ");
y++;
if(y % 4 == 0)
{
System.out.println();
}
}
for(i = 0; i >= num; i--)
{
System.out.print(i + " ");
y++;
if(y % 4 == 0)
{
System.out.println();
}
}
But thank you all again for giving my ideas.

Categories