how to solve this Java Array default initialization - java

public class ApiClass{
//The below method prints only the user entered values
public void printArray(int[] a){
for(int element : a){
//ignore because this is the default value when array is created not user entered
if(element != 0)
{
System.out.print(element+"\t");
}
}
}
}
public class Client{
public static void main(String... args){
ApiClass api = new ApiClass();
int[] input = new int[5];
input[0]= 3;
input[2]= 2;
input[3] = 1;
api.printArray(input);
}
}
This is working fine but failing for the 3,2,0 or 0,0,0 or 3,0,1 any input user enters with zero

default value for primitive int type is 0 so the uninitilized elements in array will hold 0 value,
now if you check if element is not 0 then print and if you give input 3,2,0 then it will skip 0
Better to use List
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(0);
numbers.add(3);
and now iterate the numbers
for(Integer num: numbers){
//print num, no need to check for `0` any more
}

That is not a good approach. If you have three user entries, you should make an array of length three (and not one of length five with two trailing un-used entries). There is no way to distinguish between the "default" 0 and a 0 assigned later.
Another option would be to use an Integer[], where the "default" is null, not 0 (but then you cannot distinguish between the "default" null and a null assigned later).
If you don't know the length of the array in advance, use a List<Integer> instead.

Satya:
If your problem is simply to distuingish the default 0-values from user-entered 0-values, why dont you initialize the array with a value that you know a user can never enter? (You need to make sure that this is the case).
One way is to iterate the array before and initialize, another one is to use
Arrays.fill()

Your for loop is wrong.
Should be
for(int element: a) {
if(element !=0){
System.out.println(element + "\t");
}
}
Your initial implementation never incremented the value of i.

Try with this one:
public void printArray(Integer[] a){
for(Integer element : a){
//Ignore because this is the default value when array is created not user entered
if (element != null) {
System.out.print(element.toString() + "\t");
}
}
}
public class Client{
public static void main(String... args){
ApiClass api = new ApiClass();
Integer[] input = new Integer[5];
input[0]= 3;
input[2]= 2;
input[3] = 1;
api.printArray(input);
}
}

Related

error with returning a value from a method in java

hello in the code below I am sorting (sort method) a small array to find the largest number. I then print the answer in the (display method).
But to extend my knowledge I want to mass the max value back to them main in a return statement and then print from there....simply to learn how to return a value.
package christmas;
public class maxvalue
{
public static void main(String[] args)
{
int[] data={10,90,30};
sort(data);
System.out.println("\nmax number is :");
display(data);
System.out.println(data);
}
static int display(int num[])
{
System.out.print(num[0] + " ");
return num[0];
}
static void sort(int num[])
{
int i, j, temp;
for(i=0; i<num.length-i;i++)
{
for(j=0; j<num.length-i-1;j++)
{
if(num[j]<num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
}
}
the output is:
max number is :
90 [I#4617c264
90 is the max value as printed by the display value. But after this I have a return of the max value and then I try and print the return. But instead of an integer it looks like a memory location is being printed.
Any ideas please - I am student but this is not homework - simply trying to catch up. I appreciate that there are more elegant ways to calculate the max value in an array but what I am trying to learn is the passing of arguments to and from a method.
The reason is that you are trying in your last System.out to print data, which is an array, and that's the reason why you see a memory address.Try printing display(data) and you will see as the output the desired number.
try System.out.println(data[0]);
data is your array therefore printing data without an index will only print its memory location
Instead of printing the returned value, you are printing the data array memory location:
System.out.println(data);
You should change that line with:
System.out.println(display(data));
With that line we have:
Your display method is called and it prints the max value
Your display method returns the max value
println takes that returned value and prints it
private static int sort(int[] array){
int a, b, max = 0;
for (int i = 1;//If i was 0, it would have thrown an ArrayIndexOutOfBoundsException.
i < array.length; i++){
a = array[i-1];//The first element in the array.
b = array[i];//The second one, and so on.
if (a > b) max = a;//Check the bigger number.
else max = b;
}
return max;
}
private static void display(int nr){
System.out.print(nr);//Or what you want to do with the number.
}
public static void main(String[] args){
int[] data={10,90,30};
display(sort(data));
//Or do it like this.
int max = sort(data);
display(max);
}

string array; java.lang.ArrayIndexOutOfBoundsException: 10

I have two classes that basically function as the most simplest database, where the user is supposed to enter a string and the program adds it in the array using a class that holds all the methods. Except that when i enter the first name it gives me java.lang.ArrayIndexOutOfBoundsException: 0. I know this means that no memory is being allocated for the array but i thought i did this in my second class where there is a constructer that defines the size of the array. Im not experienced enough with arrays to fix this debug on my own. Much help would be appreicated!
import java.util.*;
public class TestDatabase {
//contant value for data base 'size' of array
public static final int constant = 10;
public static void main (String[] args){
//Database object sets the array size to constant value
Database get = new Database(constant);
//input stream
Scanner in = new Scanner (System.in);
//varaibles for the count and index; prompt
int count = 0;
int index = 0;
System.out.println("Please enter 10 names to add them to the database. Name: " + (count += 1));
//while the count is lower than or equal to 10...
while(count<=10){
//input stream equal to input
String input = in.nextLine();
//if the count equals, stop the loop
if (count == 10)
{
//breaks the loop
break;
}
//prints out the current name
System.out.print(" Name: " + (count +=1));
//adds the input to the array
get.add(index,input);
//increments index by 1
index++;
}
//prints the array
get.print();
}
}
Here is my class with my all my methods:
import java.util.*;
public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
_size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
//the values of string is placed into some index of the array
userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
//prints array
System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
//sorts the array
Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
Arrays.asList(userArray).contains(value);
}
}
Your ArrayList is never instantiated properly, you need to move it into your constructor so when the new operator is called, then the arraylist is created with the size variable that is passed, so something like this:
public Database {
private String[] data;
public Database(int size){
this.data = new String[size];
}
}
With your current code, the array is created before the size is actually given, so it defaults to a size of 0.
userArray init with zero length before your constuctor set _size. Create userArray in constructor.
there next steps performed when you create class:
_size init with 0
userArray init with zero length array
_size init with size value.
Change the code as below
String[] userArray;
public Database(int size){
_size = size;
userArray = new String[_size];
}

Print only the Current Value of an array or array index

Java Novice:
I am using a for loop to iterate an array and check it's values.
For example: If the array contains the number 100. Then do something,
However if it doesn't then get the current value of the current variable.
Is it possible to get the value of the current variable when the check was made?
Currently, when I print using the else I get everything printed out.
Like this:
1
2
3
Found Something!
Please forgive my ignorance. Just experimenting:
public class MyArrayExample {
private int[] intArray = new int[] {1, 2, 3, 100};
public int[] getArrayValues() {
return intArray;
}
public static void main(String[] args)
{
MyArrayExample example = new MyArrayExample();
int[] arrayValues = example.getArrayValues();
for(int counter=0; counter<arrayValues.length; counter++) {
int current = arrayValues[counter];
if(current == 100)
{
System.out.println("Found Something!");
}
else{
System.out.println(current);
}
}
}
}
To get the value of current when the check was made, declare it outside the for loop in order to have the access to the variable value and add a boolean flag isFound:
int current = 0;
boolean isFound = false;
for(int counter=0; counter<arrayValues.length; counter++) {
current = arrayValues[counter];
if(current == 100)
{
isFound = true;
// do something
}
}
Then once the check is made you can get the value of current or print that found something:
if (isFound) {
System.out.println("Found Something!");
} else {
System.out.println("current: " + current);
}
Note. If the value you are looking for is not present in the array, current is always assigned with the last value in the array.
As an addition - you don't even have to write a loop yourself, you can just use existing array/collection methods, for example:
Integer[] intArray = new Integer[] {1, 2, 3, 100};
List<Integer> myList = Arrays.asList(intArray);
System.out.println(myList.contains(100)); // checks if 100 exists in your array
System.out.println(myList.indexOf(100)); // shows the position of the element 100

Java Bubblesort Algorithm

I am trying to use the summer to practice more Java to get better by learning how to code algorithms. I have this problem where I add elements to my ArrayList but somehow the first number I add also sets the number of positions in my list which I want to avoid. I only want the 0th index to contain the number 5. I seem to not catch a clue on how to solve this.
public class Algorithms {
private ArrayList<Integer> numbers;
public Algorithms() {
numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(4);
bubblesort();
}
public static void main(String args[]) {
new Algorithms();
}
public void bubblesort() {
System.out.println(numbers);
for (int a = 0; a < numbers.size();) {
for (int b = 1; b < numbers.size();) {
int currentNumber = numbers.get(a);
if (currentNumber > numbers.get(b)) {
//Collections.swap(numbers, currentNumber, numbers.get(b));
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
a++;
b++;
} else if (currentNumber < numbers.get(b)) {
a++;
b++;
}
System.out.println(numbers);
}
}
}
}
You are not swapping elements correctly. Instead of
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
it should be
int temp = numbers.get(a);
numbers.set(a, numbers.get(b));
numbers.set(b, temp);
The below two statements:
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
is not performing swapping. The first argument to the List#set(int, E) method is the index in the list, where you want to set the value passed as 2nd argument. You need to use a temp variable for swapping.
Also, the swapping didn't work for your commented line for the same reason. Collections#swap method take indices for swapping. So, just change:
Collections.swap(numbers, currentNumber, numbers.get(b));
to:
Collections.swap(numbers, a, b);
And please for the love of all that is holy, don't call method from inside a constructor. Remove the method invocation from inside the constructor, and move it to main method like this:
Algorithms algo = new Algorithms();
algo.bubbleSort()

Simple array copying issue

I have to make an array of 10 numbers then copy that array into a new array without the duplicates. I got it to the point where it will weed out dups but for some reason after I determine that a number is not already in the new array it wont let me put it in there. This is what I have so far. Thanks.
import java.util.*;
import java.io.*;
public class PrintingDistinctNumbers
{
public static void main(String[] args)
{
int[] array=new int[10];
int[] array2=new int[10];
int num1;
int count = 0;
boolean results;
//let the user input 10 numbers
for(int i=0;i<array.length;i++)
{
Scanner input=new Scanner(System.in);
System.out.println("please enter 10 numbers");
num1=input.nextInt();
array[i]=num1;
}
for (int j=0;j<array.length;j++)
{
results=search(array2 ,array[j],count);
if(results=false);
{
array[j]=array2[count];
count++;
break;
}
}
// just a test to make sure the numbers copied over to the new array
System.out.println(array2[0]);
}
//search the second array to see if the int is allready in it
public static boolean search(int[] array2,int value,int count2)
{
//create variables
boolean found;
//set the variables
found= false;
//search the array
for(int index=0;index<count2;index++)
{
if(array2[index]==value)
{
found=true;
break;
}
}
return found;
}
}
Without looking at the rest of your logic, this
if(results=false);
doesn't look right
is that a typo ? You need if (results == false), or more concisely, if (!results)
note the trailing semicolon, which means the following block will execute regardless of what your if clause evaluates to. The ; is creating an empty block, which is entierely valid.
Besides if (results=false) already mentioned by Brian Agnew, I see this:
array[j]=array2[count];
You overwrite the values in the array, in which you stored your input with the values of an uninitialized second array. You probably meant to do
array2[count] = array[j];
here.
There are two bugs:
The break; statement in the if block should not be there: That would break you out of the loop, but you need the loop to keep iterating over the array until all the elements have been copied.
The test is assigning false to result, not comparing it, so change to if (!result)
There are a few style issues too:
Your search method is waaaay to long; you don't need the found variable
Name your parameters with what makes sense within the method: you have array2 when there's no array or array1 in scope. Same for count2
Prefer i to index for the loop var - it's just less to type and less to read
This is more like what it should look like:
public static boolean search(int[] array, int value, int count) {
for(int i = 0; i < count; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
In your main method, why do you have one loop with i and the next with j? Make them both i - the loop variable only has scope within the loop, so there's no clash.

Categories

Resources