My code is designed to print the values if the array in order and then reverse order. However, I also have to At a minimum use the following method headers when writing your methods:
public static int printOriginalArray(int[] list)
public static int printInReverse(int[] list)
I got the code running! I get it now!! It just clicked!! Yes!!! :-) Now my method is not exactly accurate though correct? I should have 2 methods instead of 1 and I need to rewrite it so it reverses the numbers, not swaps.
public class Assignment01a {
public static void main (String[] args) {
int[] numbers = {4, 5, 6, 7};
System.out.println("The list in order is: ");
for (int num: numbers)
System.out.println(num + " ");
swap(numbers, 0, 3);
for (int num: numbers)
System.out.println(num + " ");
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr [i] = arr [j];
arr [j] = temp;
}
}
First, all methods need to be declared inside some class. Here, your swap method is being declared inside the Assignment01a class. Furthermore, there are static methods, which are declared by having the static keyword after the public keyword (as you have for your swap method). A static method can be called from main() directly (from a "static context") . Non-static methods however need to be invoked on/from object instances. These are methods without the static keyword and they can be thought of as belonging to a specific object.
Ok, now I corrected it the way you wanted it to work. Since your methods are declared so that they return int value I assumed it's for error checking. If method returns anything but 0 program will let you know something went wrong. It looks like this:
public class Assignment01a {
public static void main (String[] args) {
int[] numbers = {4, 5, 6, 7};
if (printOriginalArray(numbers) != 0)
System.out.println("ERROR!");
if (printInReverse(numbers) != 0)
System.out.println("ERROR!");
System.out.println("\nProgram completed successfully!");
}
public static int printOriginalArray(int[] list) {
System.out.println("The list in order is: ");
for (int num: list)
System.out.print(num + " ");
return 0;
}
public static int printInReverse(int[] list) {
System.out.println("\nThe list in reverse order is:");
for (int i = list.length-1; i >= 0; i--) {
System.out.print(list[i] + " ");
}
return 0;
}
}
I hope that clarified your problem, if you have any other question feel free to ask.
Related
I made a bunch of methods and encountered this part of the question:
"Test your methods in a program and include a method that reads a list, terminated by -999, into an array."
I am not sure what to do on this part and hopefully someone can show me and explain how I can do this. Here is my Code:
(NOTE: the comment showing "4-Termination Method" section is empty. That is where I'm trying to make the code)
import java.util.Scanner;
public class Problem3 {
//1-MAXIMUM METHOD//
public static int max(int[] arr)
{
int tmpMax = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > tmpMax)
{
tmpMax = arr[i];
}
}
return tmpMax;
}
//2-MINIMUM METHOD//
public static int min(int[] arr)
{
int tmpMin = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < tmpMin)
{
tmpMin = arr[i];
}
}
return tmpMin;
}
//3-MIN-MAX METHOD//
public static int[] maxMin(int[] arr)
{
int[] myArray = new int [2];
myArray[0] = min(arr);
myArray[1] = max(arr);
return myArray;
}
//4-TERMINATION METHOD//
public static int termination(int[] arr)
{
}
//5-MAIN-METHOD//
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int a, b, c, d, e;
System.out.println("Input the Numbers: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
d = input.nextInt();
e = input.nextInt();
int[] test = {a, b, c, d, e};
System.out.println("The Maximum Number is: " + min(test));
System.out.println("The Minimum Number is: " + max(test));
int [] x = maxMin(test);
System.out.println("Min: " + x[0]);
System.out.println("Max: " + x[1]);
}
}
EDIT #1:
It has been nearly 24 hours so I'll give you some more hints regarding the requirement to "include a method that reads a list..."
You want to use a loop that ends when the user inputs a value of -999. You also have to consider that the requirement is to read the values into an array so that means you will have to resize the array each time through the loop.
So your logic would go something like this:
Get the first integer from System.in and store it in a variable
Initialize an array to hold the input values, initial length 0
Begin looping until the variable from #1 equals -999
a) Resize the array from #2
b) Add the integer to the resized array
b) Read the next integer from System.in and store in the same variable as #1
END EDIT #1
I don't want to give too much away too soon - see how to ask homework questions. So please see my comment regarding the requirement "include a method that reads a list...".
I will give you a short example of how to test your code "in a program":
public class TestProblem3{
public static void main(String[] args){
testMin();
}
public static void testMin(){
int[] data = {1,2,3,4,5};
int minValue = Problem3.min(data);
if( minValue != 1 )
System.err.println("FAILURE expected 1, but actual value is "+minValue);
data = new int[]{-1,2,3,4,5};
minValue = Problem3.min(data);
if( minValue != -1 )
System.err.println("FAILURE expected -1, but actual value is "+minValue);
//More tests here!
}
//More test methods here!
}
If you're really ambitious you could learn about JUnit and/or other testing frameworks (like TestNG)
I am facing a problem where I need to sort a String array in alphabetical order. I am able to sort one array, but the problem starts when there are 2 more arrays, that correspond to the first array. Each value in each array should be in the same place, to make information not messed up. After sorting array1, it is in alphabetical order, but i don't have any idea how to make values from array2 and array3 change the positions the same like in array1 after sorting is finished.
My code so far is:
public void sort()
{
boolean finish = false;
while(finish == false){
finish = true;
for(int i=0;i<Country.length-1;i++)
{
int num = 0;
if(Country[i] != null && Country[i + 1] != null)
{
String name1=Country[i]; String name2=Country[i+1];
num=name1.compareTo(name2);
}
else if(Country[i] == null && Country[i + 1] == null){
num = 0;
}
else if(Country[i] == null){
num = 1;
}
else {
num = -1;
}
if(num>0)
{
String temp=Country[i];
Country[i]=Country[i+1];
Country[i+1]=temp;
finish=false;
}
}
}
By far the most recommended way is to re-design your program, and arrange all the related items in a single class. This is what objects are for, after all. Then you can make the object Comparable, give it a compareTo method, and sort it.
But if you are really unable to do that, what you should do is, whenever you exchange any two items in your sort array, make sure you exchange the corresponding items in the other arrays.
So, if you have arrays country, capital and headOfState, you will have to write something like:
String temp=country[i];
country[i]=country[i+1];
country[i+1]=temp;
temp=capital[i];
capital[i]=capital[i+1];
capital[i+1]=temp;
temp=headOfState[i];
headOfState[i]=headOfState[i+1];
headOfState[i+1]=temp;
This way, whenever you move anything in your main array, you'll also be moving the respective item in the other arrays, so they will stay together.
But again, it's much more preferred if you re-designed your program.
Also note the Java language conventions - variable names should not start with a capital letter, only type names should.
If you want all the array to be swaped based on the compare you did in the country array. You can just swap more than one array after one compare.
If(array1[i] > array1[i+1]){
Swap(array1[i],array1[i+1)
Swap(array2[i],array2[i+1])
}
By using a swap function, you can make it more simpler to do swaping in much more array.
You have to swap elements in Country and City arrays simultaneously.
public class BubbleSortTmp {
public String[] Country = {"z", "h", "a"};
public int[] City = {3, 2, 1};
public void printCountry() {
for (String s : Country) {
System.out.printf("%s ", s);
}
System.out.println();
}
public void printCity() {
for (int s : City) {
System.out.printf("%s ", s);
}
System.out.println();
}
public void sort() {
for (int outer = Country.length - 1; outer > 0; outer--) {
for (int inner = 0; inner < outer; inner++) {
if (Country[inner].compareTo(Country[inner+1]) > 0) {
swapCountry(inner, inner+1);
swapCity(inner, inner+1);
}
}
}
}
private void swapCountry(int first, int second) {
String tmp = Country[first];
Country[first] = Country[second];
Country[second] = tmp;
}
private void swapCity(int first, int second) {
int tmp = City[first];
City[first] = City[second];
City[second] = tmp;
}
public static void main(String[] args) {
BubbleSortTmp bs = new BubbleSortTmp();
System.out.println("Before: ");
bs.printCountry();
bs.printCity();
bs.sort();
System.out.println("After: ");
bs.printCountry();
bs.printCity();
}
}
I am trying to search an array of any data type (Int, Strings, Chars, etc...) to see if there exist an element that matches the one you input. You should return the index of the matching element. There are two classes being used.
The error I get is:
"Cannot make a static reference to the non-static method find(Object[], Object) from the type ArraySearch"
Its suggestion is to make the method static, however, doing that gives me an error in the Search class:
"Cannot make a static reference to the non-static type E".
Search Class:
public class ArraySearch<E> {
public int find (E[] array, E item) {
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(item)) {
System.out.println("There is a element " + array[i] +
" at index " + i);
index = i;
break;
}
}
return index;
}
}
Runner Class:
public class ArraySearchRunner {
public static void main(String[] args) {
String[] strings = new String[]{"Jim", "Tim", "Bob", "Greg"};
Integer[] ints = new Integer[]{1, 2, 3, 4, 5};
ArraySearch.find(strings, "Bob");
ArraySearch.find(ints, 4);
}
}
What is the best solution in this case?
Thanks,
You need to create an instance of your class to invoke the instance methods. Something like this:
class Demo {
public void show() { }
}
new Demo().show();
Now, I leave it to you to instantiate your generic class.
Also, your find() method is broken. If an element is not found, it will return an index = 0. Which is a valid index in array. You should rather initialize the index to -1:
int index = -1;
Regarding your attempt to make the method static, it will give you error, because the type parameters are not applicable for static members of a class.
From Java Generics FAQs - Angelika Langer:
The scope of a class's type parameter is the entire definition of the class, except any static members or static initializers of the class. This means that the type parameters cannot be used in the declaration of static fields or methods or in static nested types or static initializers.
public class ArraySearch<E>
{
public int find (E[] array, E item)
{
int c = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i].equals(item))
{
c++;
}
}
System.out.println("There is a element " + item +
" repeated " + c + " time(s)");
return c;
}
public static void main(String[] args)
{
String[] strings = new String[]{"Jim", "Tim", "Bob", "Greg","Bob"};
String[] strings2 = new String[]{"Jim", "Tim", "Bob", "Greg","Bob"};
Integer[] ints = new Integer[]{1, 2, 3, 4, 5,2};
Double[] dbl= new Double[] {1.2,3.6,8.4,8.4,8.4,3.6};
ArraySearch arr = new ArraySearch();
arr.find(strings, "Bob");
arr.find(strings, "Tim");
arr.find(ints, 2);
arr.find(dbl, 8.4);
enter code here
}
}
I have a problem with my code, in that it keeps saying that the constructor is undefined. I already read somewhere that I need to declare the constructor with no arguments. I just don't know how to do that.
If someone could help, I am new at java and programming. My code is below:
import java.util.*;//import library
class Input
{
public Input (int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
}
public Input enter(int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
return this;
}
}
class Show
{
public Show (int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
}
public Show print(int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
return this;
}
}
public class Assignment2
{
public static void main(String[] args)
{
//declaring variables
int startV,endingV;
int size=0;
System.out.print("Give the size of the array:");//Print message on screen
size = new Scanner(System.in).nextInt();//asking for the size of array
double[] array= new double[size]; //creation of array
System.out.print("Give the starting value of the array:");
startV = new Scanner(System.in).nextInt();//asking for the starting value of array
System.out.print("Give the ending value of the array:");
endingV = new Scanner(System.in).nextInt();//asking for the last value of array
//calling the functions from the other classes
Input enter= new Input(size,startV,endingV);
Show print= new Show(size,array);
}
}
You're close:
You have a method:
public Method enter(int size,int startV,int endingV) {
to make it a constructor it's signature must be
public Method (int size,int startV,int endingV) {
and you then have to delete the return this; statement.
Remember, constructors don't have a return type and their name is identical to the name of the class. With this information, you'll also be able to fix the Method1 constructor.
Also, please respect the Java naming conventions and have variables start with a lower-case letter to improve the readability of your code.
You need to create a
public Method(size,startV,endingV)
not
public Method enter = (size, startV, endingV)
The first is a constructor the second is a method
For class Method
the default constructor will be
public Method(){}
For class Method1
the default constructor will be
public Method1(){}
in your classes there are no constructors as the
constructor name must be will the same as class name.
enter(int size,int startV,int endingV)
and
print(int size,double[] array)
can be two methods in your classes.
also your two constructor can be -
public Method(int size,int startV,int endingV){ /..../}
and
public Method1(int size,double[] array){ /..../}
Your constructor must have the same name than your class and has no return type. So for your class Method, your constructor will simply be :
public Method(int size, int startV, int endingV)
{
// code...
}
Please also note that constructors exist to initialize your instances of objects, if you want to create a method that does a specific calcul, then yes, you'll have to do :
public int enter(int size, int startV, int endingV)
{
int result = 0;
// code to calculate, for example result = size + startV + endingV ...
return result;
}
I need to make the random array print, and it does, & then i need to make the code sort my random array and print that.
I think, i have missed something out on the code,
Can anyone help me please?
Thanks
import java.util.ArrayList;
import java.util.Random;
public class Lab5
{
public static void main(String[]args)
{
Random r = new Random();
int[]arr = new int[5];
for(int i=0;i<arr.length;i++)
{
arr[i] = Math.abs(r.nextInt()%255) +1;
System.out.print(arr[i] + "\t");
}
System.out.println();
}
public static void ShowArray(ArrayList<Integer> array) {
for (int i=0; i<array.size(); i++) {
System.out.println(array.get(i));
System.out.println("Sort A: ");
ArrayList<Integer> sortedArrayA = ThreeSorts.SortA(array);
ShowArray(sortedArrayA);
}
}
}
Random r = new Random();
int[]arr = new int[5];
for(int i=0;i<arr.length;i++)
{
arr[i] = Math.abs(r.nextInt()%255) +1;
System.out.print(arr[i] + "\t");
}
System.out.println();
Arrays.sort(arr);
for(int item: arr)
System.out.println(item);
Retrace your execution - does the code that you wrote run?
Don't forget that code in a function only runs when the function is called.
The following code may give you some useful hints:
public static void main(String[] args) {
int[] array = new int[] {3,4,65,1,43};
System.out.println(Arrays.toString(array));
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
Notes:
I skip the part related to generating random integer, because you have it
to print an array you may use Arrays.toString()
to sort an array you may use Arrays.sort()
In method main you must add ShowArray(arg).
As #Mikeb and #Belinda point out, ShowArray is not being called. Furthermore, it is an infinitely recursive function, as it calls itself without a base case to terminate; perhaps you meant to put some of the lines in the main method? I corrected the indentation on your code so as to see this better.