Java Single Dimensional Arrays - java

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");
}
}
}

Related

java sum two arrays+move the carry but index[0] wont display the last digit properly

I created a program for adding two arrays and moving the carry to the next index position , it works but when it gets to the last value index[0] if a carry is coming example: 5+6 =11 + 1(carry) = 12, i'll get in position [0] only the number 2. not the whole number 12. how can i stop the carry if it reaches to index [0] and just display the whole number?
(decimal system only)
public class SumArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size = 2;
int [] arr1 = new int [size];
int [] arr2 = new int [size];
int [] result = new int [2];
System.out.println("Array 1 : ");
for(int i =0; i<arr1.length; i++){
System.out.print("Position : " + i + " = " );
arr1[i] = input.nextInt();
}
System.out.println(Arrays.toString(arr1));
System.out.println("Array 2 : ");
for(int i =0; i<arr2.length; i++){
System.out.print("Position : " + i + " = " );
arr2[i] = input.nextInt();
}
System.out.println(Arrays.toString(arr2));
//carry sum
boolean toggle = false;
for(int i=result.length-1; i>=0; i--){
int sum=0;
int temp=0;
int carry=10;
sum = arr1[i] + arr2[i];
if (toggle == true) {
if ( sum >= carry) {
temp = sum+1 - carry;
}
else {
temp = sum+1;
}
}
else if (sum > carry) {
temp = sum - carry;
}
else{
temp = sum;
}
result[i] = temp;
toggle = sum >= carry ;
}
System.out.println("Final Array : " + Arrays.toString(result));
}
}

How can I implement a sequence of numbers in this Prime number generator?

I'm unsure of how to create a sequence of numbers that can be placed before each iteration of printed prime numbers. Thank you for any help you can offer.
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(i);
}
}
}
}
Right now, my code outputs (after the user enters their two numbers):
Counting prime numbers between 1 and 14:
3
5
7
11
13
What I need my code to look like:
Counting prime numbers between 1 and 14:
1. 3
2. 5
3. 7
4. 11
5. 13
Also, if you could see any errors or improvements I could change, I would greatly appreciate it. Thank you again!
You can use a counter and print the counter as you print the prime number. Increment the counter each time.
int counter = 1;
int flag = 0, i, j;
.....
if (flag == 1) {
System.out.format("%d. %d\n", counter, i);
counter++;
}
a simple change:
import java.util.Scanner;
public class CountingPrimes {
public static void main(String[] args) {
int flag = 0, i, j;
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the 1st number: ");
int firstNum = sc.nextInt();
System.out.println("Enter the 2nd number: ");
int secondNum = sc.nextInt();
System.out.println("Counting prime numbers between "
+ firstNum + " and " + secondNum + ":");
for (i = firstNum; i <= secondNum; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
System.out.println(++count + "." + i);
}
}
}
}
Just add a count variable and increment it whenever you output a number:
...
int count = 0;
for (i = firstNum; i <= secondNum; i++) {
...
if (flag == 1) {
count++;
System.out.format("%d. %d%n", count, i);
}
}
Declare Count before for loop
int count = 0;
and then increment the count on every prime number.
if (flag == 1) {
System.out.println(++count+". "+i);
}
}

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++;
}

Array count logic error

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);
}
}

Array sort in other arrays(JAVA)

I want to sort integers from an array and put them in separate arrays for negative numbers, odd, and even numbers.
I tried everything i could think of, I'm a beginner and I really need to solve this error.
package intarray;
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
int a[] = new int[10];
int z = 0;
int x = 0;
int y = 0;
int e[] = new int[z];
int n[] = new int[x];
int o[] = new int[y];
int i = 0;
while (i<10){
Scanner s = new Scanner(System.in);
System.out.println("Enter the number");
a[i] = s.nextInt();
if (a[i] % 2 == 0 && a[i] > 0 ){
o[y] = a[i];
y++;
}
if (a[i] % 2 != 0 && a[i] > 0 ){
e[x] = a[i];
x++;
}
if (a[i] < 0){
e[z] = a[i];
z++;
}
i++;
}
System.out.println("Odd numbers: " + o);
System.out.println("Even numbers: " + e);
System.out.println("Negative numbers: " + n);
}
}
Arrays in Java are not resizable, so you need to allocate enough size initially:
int e[] = new int[10];
int n[] = new int[10];
int o[] = new int[10];
Also, you mixed up even and odd numbers. It should be:
if (a[i] % 2 == 0 && a[i] > 0 ){
e[x] = a[i];
x++;
}
if (a[i] % 2 != 0 && a[i] > 0 ){
o[y] = a[i];
y++;
}
Also, you have a typo when storing negative number. Shuld be:
if (a[i] < 0){
n[z] = a[i];
z++;
}
And finally you cannot output array as you do. Should be:
System.out.println("Even numbers: " + Arrays.toString (e));
System.out.println("Odd numbers: " + Arrays.toString (o));
System.out.println("Negative numbers: " + Arrays.toString (n));
Here is how I would do this:
public static void main(String[] args) {
List <Integer> e = new ArrayList<> ();
List <Integer> o = new ArrayList<> ();
List <Integer> n = new ArrayList<> ();
Scanner s = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
System.out.println("Enter the number");
int a = s.nextInt ();
if (a > 0)
{
if (a % 2 == 0) e.add (a);
else o.add (a);
}
else n.add (a);
}
System.out.println("Even numbers: " + e);
System.out.println("Odd numbers: " + o);
System.out.println("Negative numbers: " + n);
}
int z = 0;
int x = 0;
int y = 0;
int e[] = new int[z];
int n[] = new int[x];
int o[] = new int[y];
You're creating arrays with size 0. While the syntax is ok (code will compile), you cannot use your arrays, since they're of size 0 (hence you can't put anything on them). Remember that in Java, the size of an array cannot be changed after initialization.
I would suggest you read up on List, which is basically an array with an arbitrary size (expands to your needs).
For example:
List<Integer> positiveNumbers = new ArrayList<Integer>();
List<Integer> negativeNumbers = new ArrayList<Integer>();
...
You can add items in your List like this:
positiveNumbers.add(<your integer here>);
I know it's a bit of a re-write, but how about this. This way you have a better system that you can extend in the future easily.
package intarray;
import java.util.Scanner;
import java.util.ArrayList;
public class Input {
private Integer defaultSize = 10;
ArrayList<Integer> theArray = new ArrayList<Integer>(defaultSize);
ArrayList<Integer> counts = new ArrayList<Integer>(3);
// Here you have your main where you just call stuff in turn.
// You could also swap in any other method of filling in your array or counting it.
public static void main(String[] args) {
getInput();
count();
outputCounts();
}
public void getInput() {
for (int index = 0; index < defaultSize; index++) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number");
theArray.add(s.nextInt();)
}
}
public void count() {
for (int i = 0; i < defaultSize; i++) {
if (theArray.get(i) < 0) {
counts.set(counts.get(0) + 1);
} else if (theArray.get(i) == 0) {
counts.set(counts.get(1) + 1);
} else {
counts.set(counts.get(2) + 1);
}
}
}
public void outputCounts() {
System.out.println("There were " + counts.get(0) + " negative numbers.");
System.out.println("There were " + counts.get(1) + " posative numbers.");
System.out.println("There were " + counts.get(0) + " instances of the number 0.");
}
}

Categories