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.");
}
}
Related
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");
}
}
}
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));
}
}
I'm working on a game, much like the Math Dice problem, albeit a bit different. The user rolls a 20 sided die, then 5 more dice following that. To make things simpler, the user cannot reorder the dice, so if they roll 1 2 3 4 5, they can't do operations like 1 + 3 + 2 + 5 + 4. The question is if, using addition, subtraction, and multiplication, can they reach the target number from the 20 sided die?
Now, I know how to do this, just generate a permutation of all possible addition, subtraction, and multiplication of the 5 numbers, but it's the implementing of the solution that's getting me. I've hit a roadblock after a couple tries, so any help is appreciated.
edit: This is my current implementation, without the multiplication, and it isn't working quite right.
import java.util.ArrayList;
import java.util.Scanner;
public class targetDice {
public static void main(String[] args) {
ArrayList<Integer> rolls = new ArrayList<Integer>(); // Array to hold the rolls
ArrayList<Integer> d20 = new ArrayList<Integer>(); // Array to hold all the d20 rolls
Scanner sc = new Scanner(System.in);
int answer = 0;
String record = "";
while (sc.hasNextInt()) {
d20.add(sc.nextInt()); // Adds the d20 rolls
rolls.add(sc.nextInt()); // Adds the first roll
rolls.add(sc.nextInt()); // Adds the second roll
rolls.add(sc.nextInt()); // Adds the third roll
rolls.add(sc.nextInt()); // Adds the fourth roll
rolls.add(sc.nextInt()); // Adds the fifth roll
} // End while loop
for (int i = 0; i < d20.size(); i++) { // Number of times we need to compute: number of d20 rolls
answer = rolls.get(0);
for (int j = 0; j < rolls.subList(0, 5).size(); j++) { // Go through each roll given
if (d20.get(i) > answer || d20.get(i).equals(answer)) { // If the d20 roll is higher than the first roll or if it's equal
answer += rolls.get(j);// then take the running total and add it
record += " + ";
} else if (d20.get(i) < answer) {
answer -= rolls.get(j);
record += " - ";
}
}
System.out.println(answer);
//TODO: This if else block is our final product. It should be fine.
if (answer == d20.get(i)) // If the combo is equal the d20 roll
System.out.println("Solution"); // Print solution
else
System.out.println("No Solution"); // Otherwise print no solution
rolls.subList(0, 5).clear(); // Clears out the first 5 elements to make coding easier
answer = 0; // Reset the answer var
System.out.println(record);
} // End For loop
} // End main
} // End class
It's set up so that the user can do the rolls more than once, if they were to try this game 3 times, they can do all three then get all three answers at once.
If you want to see it in a different way, here's the pastebin: http://pastebin.com/PRB0NKpN
edit 2: Here's my final solution. A bit bruce-forcey.
import java.util.ArrayList;
import java.util.Scanner;
public class testClass {
public static void main(String[] args) {
ArrayList<Integer> d20 = new ArrayList<Integer>();
ArrayList<Integer> rolls = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
d20.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
}
int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
for (int x = 0; x < d20.size(); x++) {
int wright = 0, rong = 0;
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 4; j++) {
for (int k = 1; k < 4; k++) {
for (int m = 1; m < 4; m++) {
if (i == 1) {
num1 = rolls.get(0) + rolls.get(1);
} else if (i == 2) {
num1 = rolls.get(0) - rolls.get(1);
} else if (i == 3) {
num1 = rolls.get(0) * rolls.get(1);
}
if (j == 1) {
num2 = num1 + rolls.get(2);
} else if (j == 2) {
num2 = num1 - rolls.get(2);
} else if (j == 3) {
num2 = num1 - rolls.get(2);
}
if (k == 1) {
num3 = num2 + rolls.get(3);
} else if (k == 2) {
num3 = num2 - rolls.get(3);
} else if (k == 3) {
num3 = num2 * rolls.get(3);
}
if (m == 1) {
num4 = num3 + rolls.get(4);
} else if (m == 2) {
num4 = num3 - rolls.get(4);
} else if (m == 3) {
num4 = num3 * rolls.get(4);
}
if (d20.get(x) == num4) {
wright = 1;
}
}
}
}
}
if (wright == 1)
System.out.println("Case " + (x+1) + ": Solution");
else
System.out.println("Case " + (x+1) + ": No Solution");
rolls.subList(0, 5).clear();
}
}
}
I see you find answer by yourself, but I also tried to solve your problem, and I decide to post here an another solution in any case:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Test test = new Test();
test.combineOperators();
Scanner scanner = new Scanner(System.in);
int result = scanner.nextInt(); //get input
int[] numbers = new int[5];
for(int i = 0; i <5; i++){
numbers[i] = scanner.nextInt();
}
ArrayList<Integer> results = test.operationsOnArrays(numbers, test.combineOperators()); //check for results
if(results.contains(result)){
System.out.println(result + " is a possible solution");
}else{
System.out.println(result + " is not a possible solution");
}
}
public ArrayList<String[]> combineOperators(){ //create all possible combinations of operators
String[] signs = {"+","-","*"};
ArrayList<String[]> combinations = new ArrayList<String[]>();
for(String a : signs){
for (String b : signs){
for(String c : signs){
for(String d: signs){
String[]temp = {a,b,c,d};
combinations.add(temp);
}
}
}
}
return combinations;
}
public ArrayList operationsOnArrays(int[] num, ArrayList<String[]> combinations){ //do the math with every combination on given ints
ArrayList<Integer> list = new ArrayList<Integer>();
for(String[] operators : combinations){ //for every operators combination
int result = num[0];
for(int i = 0; i<=3 ; i++){
result = doTheMath(operators[i],result,num[i+1]); // take two ints and operator
}
list.add(result);
}
return list;
}
public int doTheMath(String operator, int prev, int next){ // it take two ints from input array, and do operation
if(operator.equals("+")){ // determined by a taken operator
return prev + next;
}else if(operator.equals("-")){
return prev - next;
}else if(operator.equals("*")){
return prev *next;
}
return 0;
}
}
I think that this way, it is vary simple to expand, for more numbers or operator, or even to implement reordering of input numbers.
I populate an Arraylist<Integer> with palindromic numbers. I then retrieve a user-specified element from the list via its get() method, and print that number. I am trying to use a while loop to allow the user to select multiple elements, until he enters "0", but instead the program exits after the first selection. How can I make it repeat?
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
ArrayList<Integer> str = new ArrayList<Integer>();
for (int i = 1; i <= 1000; i++) {
int a = i;
int b = inverse(a);
if (a == b) {
str.add(a);
}
}
int num = cin.nextInt();
do {
int getnum = str.get(num - 1);
System.out.println(getnum);
}
while(num == 0);
}
public static int inverse(int x) {
int inv = 0;
while (x > 0) {
inv = inv * 10 + x % 10;
x = x / 10;
}
return inv;
}
Your loop test should probably be while it's not equal to zero. Also, you need to get num again.
// int num = cin.nextInt();
int num;
do{
num = cin.nextInt();
System.out.println("num is " + num);
if (num > 0 && num <= str.size()) {
System.out.println(str.get(num - 1));
}
} while(num != 0);
I need to factorize a number like 24 to 1,2,2,2,3. My method for that:
static int[] factorsOf (int val) {
int index = 0;
int []numArray = new int[index];
System.out.println("\nThe factors of " + val + " are:");
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
numArray1 [index] = i;
index++;
}
}
return numArray;
}
however, it is not working. Can anyone help me for that?
You have a few errors, you cannot create int array without size. I used array list instead.
static Integer[] factorsOf(int val) {
List<Integer> numArray = new ArrayList<Integer>();
System.out.println("\nThe factors of " + val + " are:");
for (int i = 2; i <= Math.ceil(Math.sqrt(val)); i++) {
if (val % i == 0) {
numArray.add(i);
val /= i;
System.out.print(i + ", ");
}
}
numArray.add(val);
System.out.print(val);
return numArray.toArray(new Integer[numArray.size()]);
}
Full program using int[] according to your request.
public class Test2 {
public static void main(String[] args) {
int val = 5;
int [] result = factorsOf(val);
System.out.println("\nThe factors of " + val + " are:");
for(int i = 0; i < result.length && result[i] != 0; i ++){
System.out.println(result[i] + " ");
}
}
static int[] factorsOf(int val) {
int limit = (int) Math.ceil(Math.sqrt(val));
int [] numArray = new int[limit];
int index = 0;
for (int i = 1; i <= limit; i++) {
if (val % i == 0) {
numArray[index++] = i;
val /= i;
}
}
numArray[index] = val;
return numArray;
}
}
public int[] primeFactors(int num)
{
ArrayList<Integer> factors = new ArrayList<Integer>();
factors.add(1);
for (int a = 2; num>1; )
if (num%a==0)
{
factors.add(a);
num/=a;
}
else
a++;
int[] out = new int[factors.size()];
for (int a = 0; a < out.length; a++)
out[a] = factors.get(a);
return out;
}
Are you looking a more faster way?:
static int[] getFactors(int value) {
int[] a = new int[31]; // 2^31
int i = 0, j;
int num = value;
while (num % 2 == 0) {
a[i++] = 2;
num /= 2;
}
j = 3;
while (j <= Math.sqrt(num) + 1) {
if (num % j == 0) {
a[i++] = j;
num /= j;
} else {
j += 2;
}
}
if (num > 1) {
a[i++] = num;
}
int[] b = Arrays.copyOf(a, i);
return b;
}
Most of the approaches suggested here have 0(n) time complexity. This can be easily resolved using binary search approach with 0(log n) time complexity.
What do you basically are looking for is called Prime Factors (although 1 is not considered among prime factors).
//finding any occurrence of the no by binary search
static int[] primeFactors(int number) {
List<Integer> al = new ArrayList<Integer>();
//since you wanted 1 in the res adn every no will be divided by 1;
al.add(1);
for(int i = 2; i< number; i++) {
while(number%i == 0) {
al.add(i);
number = number/i;
}
}
if(number >2)
al.add(number);
int[] res = new int[al.size()];
for(int i=0; i<al.size(); i++)
res[i] = al.get(i);
return res;
}
Say input is 24, we keep dividing the input by 2 till all multiples of 2 are gone, the increase i to 3
Here is a link to the working code: http://tpcg.io/AWH2TJ
A Working example
public class Main
{
public static void main(String[] args)
{
System.out.println(factorsOf(24));
}
static List<Integer> factorsOf (int val) {
List<Integer> factors = new ArrayList<Integer>();
for(int i=1; i <= val/2; i++)
{
if(val % i == 0)
{
factors.add(i);
}
}
return factors;
}
}
Rework an algorithm for working with big numbers using BigInteger class. Try this:
import java.math.BigInteger;
class NumbersFactorization {
public void printPrimeNumbers(String bigNumber) {
BigInteger number = new BigInteger(bigNumber);
for (BigInteger i = BigInteger.TWO; i.compareTo(number) <= 0; i = i.add(BigInteger.ONE)) {
while(number.remainder(i) == BigInteger.ZERO) {
System.out.print(i + " ");
number = number.divide(i);
}
}
if (number.compareTo(BigInteger.TWO) > 0) System.out.println(number);
}
}
You just missed one step in if. Following code would be correct:
System.out.println("\nThe factors of " + val + " are:");
You can take a square root of val for comparison and start iterator by value 2
if(val % i == 0)
{
numArray1 [index] = i;
val=val/i; //add this
index++;
}
but here you need to check if index is 2,it is prime.