So I was tasked with asking the user to input 10 numbers into an array and then printing the numbers in order and reverse order using a tester class and not just the main.
I'm having problems with how to return the array that has been passed. Here's my code so far:
public class PrintIt
{
static int[] numbers = new int[10];
static int i = 0;
public static int PrintOrder()
{
System.out.println("\nList of numbers in order: \n");
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
return ;
}
public static int PrintReverse()
{
System.out.println("\nList of numbers in reverse order: \n");
for (int i = numbers.length - 1; i >= 0; i--)
{
System.out.println(numbers[i]);
}
return ;
}
}
and the tester class:
import java.util.Scanner;
public class PrintItTester
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int i = 0;
int[] numbers = new int[10];
System.out.println("\nPlease input " + 10 + " numbers.");
for (i=0; i < numbers.length; i++)
{
PrintIt.numbers[i] = input.nextInt();
}
System.out.print(PrintIt.PrintOrder());
System.out.print(PrintIt.PrintReverse());
}
}
When I run the code with numbers[i] in the return it reads i as being 0 and only outputs the first element in the array. I've looked for a long time and I can't figure this out.
I know, obviously, that there needs to be something returned, but whatever I put doesn't work. For example, when I try to return the array, numbers[i], it only returns the first element because the variable has a value of 0.
You have several problems in your code:
The declaration int[] numbers = new int[10]; in the main is useless. Remove it, and replace numbers.length with PrintIt.numbers.length
Your methods return ints, not arrays. Make them void, and call them without System.out.print.
Remove the unnecessary return statements from the PrintOrder and PrintReverse methods.
This should fix the problem (demo).
Related
I'm unsure how do I call my code so that it matches my randomizer. My randomizer basically generates a number of random integers in an array and prints them like so.
Edit: If i wasn't clear, i want to call my randomizer into both the methods of the insertion sort class!
I tried using the insertion sort implementation i grabbed from geeks4geeks. They all have the parameter int[arr].
This is my code
public class randomArr {
public void randomizer(){
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
}
}
This is what i want to happen basically:
As you can see im calling sort and print array with my "intArr". How do i call my method with the given methods?
I have commented out the object i made using my method but if i were to leave it in, how would i use that object to call sort() and printarray()?
public class insertionSort {
public static void main(String[] args){
//randomArr arry = new randomArr(); \\the object of my method
//arry.randomizer());
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
sort(intArr);
printArray(intArr);
}
public static void sort(int arr[]){
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + ", ");
System.out.println();
}
}
Ok if you want to call the method of one class into another, you simply need to call it by adding the methods name next to the object of that class with a period in between like so ("object.method()"). So what you would do is:
import java.util.*;
class randomArr {
public int[] randomizer()
{
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
return intArr;
}
}
class Stack
{
public static void main(String[] args)
{
randomArr rArr = new randomArr();
int[] intArr = rArr.randomizer();
}
}
this way you can make that array in your other class and use it in your new class.
If you want to call the methods of insertionSort class you can call them without an object since they are static. You cannot use the object of another class to call a method not belonging to that object's class.
You can use insertionSort's methods in the randomArr class by creating it's object in the randomArr class and vice versa. But an object can only access the methods of it's own class.
you want to call method in another class you can create object of that class and then using the object reference you can call available the methods from that class.
insertionSort object = new insertionSort();
object.sort(intArr);
object.printArray(intArr);
As you defined sort and printArry are static methods , you can directly invoke them in your main method.
I am trying to create a method that will accept the users input for the amount of elements they would like in an array, and the numbers to input for the array.
So far I have the main method which accepts the input from the console using the following code, after that I am not 100% sure if the method I need to create should return an int array or should just print out the results.
import java.util.Scanner;
public class Lab {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input amount desired in Array 1");`
int a = input.nextInt();
int [] array1 = new int[a];
for (int i = 0; i < array1.length; i++) {
System.out.println("Input a number");
array1[i] = input.nextInt();}
System.out.println();}
public int swapPairs(int [] array)
Ok, so You just do this:
public void swapPairs(int [] array){
for(int i = 0; i < array.length(); i += 2){
if(i != array.length - 1)
System.out.print(array[i] + " " + array[i+1]);
}
if(array.length % 2 == 1) System.out.print(" " + array[array.length - 1]);
It really depends on what you want to achieve. If you need only to see the results the print is enough but if you return the array you can operate on the one that is changed as you wanted
I've been asked to do the following problem:
Implement a method that accepts an array of integers as input and returns the sum of all of the elements in the array as output.
this is what i have(the entire program):
import java.util.*;
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
every time I try to call the method "sum" in the main method it gives me an error. I have tried every possible way I've seen on the internet to call the method. I'm not sure how I'm supposed to call it or if it is an issue because I have an array passed to the method.
Someone please help! and if you see that i've done something incorrectly, please let me know! thanks
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
// this works
System.out.println("sum is " + sum(array));
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
I'm having some trouble sorting an array. I'm trying to sort it in ascending order.
My task is to get a series of integers from the user and store them into an array, then display them back to the user in ascending order. I was fine getting input from the user, storing it in the array and displaying them back. I was able to run my code and get the results I wanted but as far as getting the integers in the array in ascending order using selection sort, I was having a lot of difficulty with that.
The size of the array depends on the value that the user inputs, so it is set to the variable numValues rather than a number.
I get an error with the sort method I created. I'm getting syntax errors and void is an invalid type. I think I'm missing something and I'm not sure how to go about fixing this. If someone can point me in the right direction. Any help would be appreciated.
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("Here are the values you've entered, in ascending order");
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
} //End for
} // End method sort
keyboard.close(); // To close Scanner object
} //End method main
You cannot have another method inside main. Get the method sort(int[] values) out of main, and call it inside main.
You had another problem. Inside your sort method:
System.out.print(values[scan] + " ");
scan has to be replaced by n.
Here is the completed code:
import java.util.*;
public class Project {
public static void main(String[] args) {
int numValues; // The number of values user has
int [] values; // Array declaration for values
Scanner keyboard = new Scanner(System.in); // Scanner object to get input from user
System.out.println("How many values do you have?"); // To get number of values for array
numValues = keyboard.nextInt();
/*
* Array to hold number of values
*/
values = new int [numValues];
/*
* Loop to gather integer values
*/
for (int n=0; n < values.length; n++ )
{
System.out.print("Enter value " + (n+1) + ":" );
values[n] = keyboard.nextInt();
} //End for loop
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + " ");
}
System.out.println("Here are the values you've entered, in ascending order");
sort(values);
keyboard.close(); // To close Scanner object
}
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
} //End for
} // End method sort
} // End class Project
Your program will not executed or will not display correct result due to some reasons.
You are using "private static void sort(int[] values)" method in main method and it's not possible because we can't define method in another method. Either you have to create a separate method outside of main method or you can use sorting functionality in your main method also.
Another mistake is in below code. You are using scan variable for displaying result in ascending order. Here is should be n.
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
}
Your logic is correct. But it's little bit large for selection sort. Below is small way to do this.
public class SelectionSort
{
public static void main(String[]args)
{
int [] values = {15,14,13,12,11};
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("\nHere are the values you've entered, in ascending order");
sort(values);
}
private static void sort(int[] values)
{
int index = 0;
int index2 = 0;
int temp = 0;
for(index=0; index<values.length; index++)
{
for(index2 = index+1; index2< values.length; index2++)
{
if(values[index] > values[index2])
{
temp = values[index];
values[index]= values[index2];
values[index2] = temp;
}
}
}
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
}
}
}
int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
//the outer loop will switch the number
for(int i=0;i<arrayToSort.length;i++){
int indexSmal=i;
//the inner loop will search for the biggest number
for(int j=i+1;j<arrayToSort.length;j++){
//search for biggest number index starting from i index
if(arrayToSort[j]>arrayToSort[indexSmal]){
indexSmal=j;
}
}//end loop
//swap the number
int smallNum=arrayToSort[indexSmal];
arrayToSort[indexSmal]=arrayToSort[i];
arrayToSort[i]=smallNum;
}// end loop
for(int i=0;i<arrayToSort.length;i++){
System.out.print(arrayToSort[i]+", ");
}
I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!