I want to create a program that reads int values from the user until a value that is not an int is introduced. Then i want to get how many numbers are equal.
I tried this code
import java.util.Scanner;
public class Equals {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Scanner input = keyboard;
int index = 0;
int equals = 0;
while(keyboard.hasNextInt()){
keyboard.nextInt();
index++;
}
int[] equals = new int[index];
for(int i = 0 ; i < index ; i++){
int aux = input.nextInt();
values[i] = aux;
for(int b = 0 ; b < index ; b++){
if(aux == values[b]){
equals++;
}
}
}
System.out.print(equals);
}
}
This code doesnt work because the keyboard scanner only gets the number of values introduced by the user and i use that for the array size but i cant get each individual value to compare. I cant use array lists.
If you can't use array lists, what can you use? Can you use this?
int[] values = new int[0];
while(keyboard.hasNextInt()){
values = Arrays.copyOf(values, values.length + 1);
values[values.length-1] = keyboard.nextInt();
index++;
}
And if you aren't allowed to do the arrays class, you can resize the array manually like this, and use this function instead of Arrays.copyOf:
private int[] resize(int[]s, int capacity) {
int[] copy = new int[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
s = copy;
}
return copy;
}
Related
I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}
I need to find the largest prime number of a given array when adding two numbers in an array,so I decided to add all possible sums first and displayed it. Now I want to take those output elements to a new array.Please help me solve this problem.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int noOfElem = scanner.nextInt();
int[] array = new int[noOfElem];
int[][] newArray = new int[5][4];
int i=0;
while(scanner.hasNextInt()){
array[i] = scanner.nextInt();
i++;
if(i == noOfElem){
break;
}
}
for (int a = 0; a < array.length; a++)
{
for (int b = a+1; b < array.length; b++) {
int m = array[a] + array[b];
newArray[a][b] =
}
}
}
}
Not quite sure what the problem is here, just do
newArray[a][b] = m;
This stores all sums of all 'a's and 'b's such that newArray[a][b] is the sum of array[a] + array[b]
Disclaimer: Still very new to code and have only basic skills with java. Trying to learn as much as i can on my own and from others. Not currently studying at uni.
Hello everyone.
I am trying to create an array with a small capacity (5 integers) to store a randomly generated integer in each array element. The randomly generated integer is in a set range (0-75) which ive no issue with.
What i cant figure out how to do is how to Generate a new integer, then check it against the current existing integers in each array element, before storing it and moving on to the next.
What i tried was this:
public class ItemSet
{
public static void main(String []args)
{
int[] itemSet;
itemSet = new int[5];
itemSet[0] = 0; /* to initialise the array elements. Im not sure if i actually have to do this or not */
itemSet[1] = 0;
itemSet[2] = 0;
itemSet[3] = 0;
itemSet[4] = 0;
int count = 1;
int assignItem = 0;
int countTwo = 1;
while (count > 5) {
while (countTwo == 1) {
assignItem = (int)(Math.random()*76);
// here is where i get totally lost
if (assignItem.compareTo(itemSet)) {
countTwo = 1;
} else {
itemSet[(count--)] = assignItem;
countTwo = 0;
}
}
count = count++;
}
}
}
Ive been looking at this so long my head is starting to hurt. I'd appreciate any advice you can give me. :) Thank you in advance. xx
Edit: Couldnt find the solution i needed in any of the "how can i test if an array contains a certain value" type questions, because i need to be able to have the number randomise again before it stores itself in the array element if it does happen to be the same as another previously generated integer.
You are doing too much to just fill an array. To fill an array, try using a "for" loop like so:
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
}
}
}
To print the values stored in the array, try using an enhanced-for loop:
for (int element : itemSet) {
System.out.println(element);
}
To check the values BEFORE storing the next integer, (say to see ensure that the new stored value would be unique) you could use a nested for loop that starts at the value beneath the outer loop and walks backwards, comparing each value that came before to the value that was just stored, and if they are the same, it will decrement the outer counter which will then override the data on the next loop:
import java.util.Arrays; // you need this to use Arrays.toString()
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
for (int j = i - 1; j >= 0; j--) {
if (itemSet[j] == itemSet[i]) {
System.out.println("Comparing " + itemSet[j] +
" and " + itemSet[i]);
i--;
break; // not really needed but illustrates a way to exit a loop immediately
}
}
}
// this is a handy way to print all the data in an array quickly
System.out.println(Arrays.toString(itemSet));
}
}
public static void main (String[] args){
//you dont need to initialize the array with zeros
int[] itemSet = new int[5];
int counter = 0;
while(counter < itemSet.length){
int random = (int)(Math.random() * 76);
//checks if the array already contains the random number
if(!Arrays.asList(itemSet).contains(random)){
itemSet[counter] = random;
counter++;
}
}
//print the array
for(int i : itemSet) System.out.println(i);
}
There are many ways you could solve this problem, I would suggest using a helping method that looks for duplicates in your array. This would be a working example:
public static void main(String[] args) {
int[] itemSet;
itemSet = new int[5];
int assignItem;
for (int i = 0; i < 5; i++) {
assignItem = (int)(Math.random()*76);
if(!duplicate(assignItem,itemSet,i)){
itemSet[i] = assignItem;
}
}
}
private static boolean duplicate(int assignItem, int[] itemSet, int i) {
for (int j = 0; j < i; j++) {
if (assignItem == itemSet[j])
return true;
}
return false;
}
The most straight forward way would be checking through the array for existing value before inserting the current random value.
Generate a random value
Check if value exists in array
If already exist in array, generate another value
If not exist in array, set value to current element
In codes:
public static void main(String[] args){
int idx = 0;
int[] myArray = new int[5];
Random rnd = new Random();
int val = rnd.nextInt(76);
do{
if(numExistInArray(val, myArray))
val = rnd.nextInt(76); //if val exist in array, generate another number
else
myArray[idx++] = val; //if val not exist in array, fill array
}while(idx != myArray.length); //do not exit loop till all numbers are filled
}
public static boolean numExistInArray(int val, int[] array){
for(int x=0; x<array.length; x++)
if(array[x] == val)
return true;
return false;
}
I had a hard time understanding what youre asking for but ill give it a go anyway hoping this is what you want:
for (int count = 0; count < 5 ; count++) {
assignItem = (int)(Math.random()*76);
if (assignItem==itemSet[count]&&itemSet[count]!=0) {
//If true do this
}
else {
itemSet[count] = assignItem;
}
}
Checking if the generated number is equal to a position and if the position is empty (0) if its not equal (a new number) then it will assign value to your array.
If you know your set range (which is 0-75) and space isn't an issue, I would suggest maintaining a pool of unused integers. This would guarantee each value is unique, and would avoid iterating over your array of integers to check for duplicates:
public static void main(String[] args) {
List<Integer> unusedNumbers = new ArrayList();
// Populate list with values
for (int i = 0; i <= 75; i++) unusedNumbers.add(i);
int[] itemSet = new int[5];
for (int i = 0; i < 5; i++) {
int randomIndex = (int) (Math.random() * unusedNumbers.size());
int randomInt = unusedNumbers.remove(randomIndex);
itemSet[i] = randomInt;
}
}
So I need to create a new array that swaps the first and last values of my existing array. Here's what I have so far:
import java.util.Scanner;
import java.util.Arrays;
public class P9_ArrayManipulate
{ public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
int total = 0;
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
System.out.println("Your reversed array is "+reverseArray(array));
System.out.println("Your swapped array is "+swapArray(array));
System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println("The program has finished calling array methods.");
}
public static int []reverseArray(int []array)
{ int[] reversed = new int[array.length];
int i;
for(i=0; i < array.length; i++)
{
reversed[i] = array[(array.length - i -1)];
}
return reversed;
}
public static int []swapArray (int []array)
{
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
public static int []evenArray(int []array)
{ for (int i = 0; i < array.length;i++){
if (array[i]%2 !=0)
{array[i] = 0;}
i++;}
return array;
}
}
Everything compiles correctly (as far as I can tell), but I'm getting a weird run time error. After seven inputs, I get this as my output:
Your reversed array is [I#b4d079
Your swapped array is [I#3644d1
Your array without even numbers is [I#3644d1
The program has finished calling array methods.
It would be much easier to just swap the first and last values of the array passed in to the swapArray() function and return that instead of creating a new array.
Something like the following will work (and it doesn't create a new variable to facilitate swapping):
public static int[] swapArray(int[] array) {
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
You have to import Arrays from java.util.Arrays
You may use the following answer to merge the arrays in swapArray() method
How can I concatenate two arrays in Java?
Try something like this:
*Edit: If its a must to create new array, just create int newarray[] = method(); instead of array[]=method();
import java.util.Scanner;
public class Array
{
public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
array = reverseArray(array);
System.out.println("Your reversed array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println();
array = swapArray(array);
System.out.println("Your swapped array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
// System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println();
System.out.println("The program has finished calling array methods.");
}
public static int[] reverseArray(int []array)
{ int left = 0;
int right = array.length-1;
while(left<right){
int reverse = array[left];
array[left]=array[right];
array[right] = reverse;
left++;
right--;
}
return array;
}
public static int []swapArray (int []array)
{
int help = 0;
help = array[0];
array[0] = array[6];
array[6] = help;
return array;
}
}
I just learned the array function in Java and now I wanted to store numbers from 1-19 in an array but don't know the right way to do it without the userinput function. Here is what I got, can you tell me if it is the right way to store number in array?
public class ArrayQuestion1 {
public static void main(String[] args) {
int a=0;
int array[] = new int [20];
for ( array[a]=1; array[a]<=19; array[a]++){
System.out.println(array[a]);
}
}
}
You would do something like this to fill your array with consecutive numbers from 0-19
public class ArrayQuestion1 {
public static void main(String[] args) {
int array[] = new int [20];
for (int a = 0; a < array.length; a++){
array[a] = a;
}
}
}
To store userinputs to int array you can do
int array[] = new int [20];
Scanner scanner=new Scanner(System.in);
for ( i=0; i<array.length; i++){
array[i]=scanner.nextInt();
}
If you want to store number from 0 to 19 you can do
int array[] = new int [20];
for ( i=0; i<array.length; i++){
array[i]=i;
}
public static void main(String[] args) {
int array[] = new int[20];
for (int i = 1; i < array.length; i++){
array[i] = i;
}
//To print all the elements in the array.
for(int j=1; i< array.length; j++){
system.out.println(array[j]);
}
}
You can insert into the array using the above method and can view the contents of array also.
If you want to add consecutive numbers you can use a simple for loop and to see them on the screen you can just iterate your array. That is all. Hope this can help you!
class Main {
public static void main(String[] args) {
int a=0;
int array[] = new int [20];
for(int i = 0 ; i < array.length ; i++){
array[i] = i;
}
for(int x : array){
System.out.println(x);
}
}
}
If you don't want user input for array , you have to store numbers manually in the array like ,
int a=0;
int array[] = new int [20];
for ( a=1;a<=19; a++){
array[a]=a;
}
above code will store 0 to 19 in your array . than you can use below for loop to print it
for ( a=1; a<=19; a++){
System.out.println(array[a]);
}
To use an array you have to declare it.
int array[] = new int [19];
If you want 19 numbers, then use an array with 19 elements.
Then you have to populate each number in the array. To obtain it, just use an index in your array:
array[index] = value
For example:
for ( int i=0; i<array.lenght; i++){
array[i] = xx;
}
Pay attention. The first index in your array is 0 (not 1)