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)
Related
I was trying to perform sorting of integers in an array and it worked fine.
But when i try to modify the program by including a "pass by reference" concept via a method, it is throwing error "cannot find symbol".
I am new to JAVA and learning by my own, Please help me with what I am doing wrong here.
import java.util.*;
import java.io.*;
public class Sort {
public static void main(String[] args) {
Sort obj = new Sort();
Scanner in = new Scanner(System.in);
int i, p, k, arr[];
arr = new int[10];
System.out.println("Enter the numbers for sorting \n");
for (i = 0; i < 5; i++) {
arr[i] = in.nextInt();
}
for (i = 0; i < 5; i++) {
for (p = 0; p < 5; p++) {
if (arr[i] < arr[p]) {
/*
* moving the below block for swapping to a new method. k =
* arr[i]; arr[i]= arr[p]; arr[p]= k;
*/
obj.swap(obj);
}
}
}
System.out.println("\n");
for (i = 0; i < 5; i++)
System.out.println(arr[i]);
}
public void swap(Sort m) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
}
The error I am getting is :
"Sort.java:44: error: cannot find symbol
m.k = m.arr[i];
^
"
Similarly 10 such errors for other variables as well.
You are trying to use index variables (i and p) that don't exist in the context you are trying to use them (inside swap() method body) as well as members of Sort (k and arr) which don't exist. The scope of all these, you have limited to the method body of main():-
public void swap(Sort m) {
m.k = m.arr[i]; //No 'i' in swap(). No 'k' or 'arr' in 'm'(an instance of 'Sort')
m.arr[i] = m.arr[p]; //No 'p' in swap()
m.arr[p] = m.k;
}
Short-term Solution
Change your swap() method to
//Now accepting in i and p
public void swap(Sort m, int i, int p) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
then call it like this
obj.swap(obj, i, p); //pass in i and p
and move your Sort variables to be accessible members of Sort
public class Sort {
public static int k; //now accessible with m.k
public static int[] arr = new int[10]; //now accessible with m.arr
...
}
Lastly, is it intentional that your array is 10 long but you only fill it with 5 numbers?
Pass-by-Reference
There is no "pass-by-reference" in Java. Everything is passed by value. The confusing thing is that what is passed by value is technically a reference to the object, meaning you get strange effects like you can edit the object but not reassign it.
Solution: move the stuff back from the swap method to where it was.
Alternatively, provide the necessary values as parameters to swap.
I have these two code for the deletion of an element from an array ,but there is just one difference the these two for loops for(int k=i;k< l-1;k++)
and for(int k =i;k< l;k++) in first we are de-crementing the size of the length of an array but in second we are not. Both the code are same else and does its deletion job fine. But I couldn't get the difference.
1st
import java.util.Scanner;
public class SearchDeletion1 {
public static void main(String[] args) {
int []a = new int[10];
a[0]=33;
a[1]=11;
a[2]=22;
a[3]=333;
a[4]=343;
a[5]=233;
a[6]=373;
a[7]=3223;
a[8]=313;
a[9]=332;
int i;
System.out.println();
int l=a.length;
Scanner s = new Scanner(System.in);
System.out.println("Enter the item to be searched");
int e = s.nextInt();
//searching
for(i=0;i<l;i++)
if(a[i]==e)
break;
if(i==a.length)
System.out.println("couldn't found");
else
System.out.println("found at position "+"a["+i+"]");
//deleting
for(int k=i;k<l-1;k++)
a[k]=a[k+1];
l--;
System.out.println("item deleted and new array");
for(int q=0;q<l;q++){
System.out.println("a["+q+"]"+"="+a[q]);
}
}
}
2nd
import java.util.Scanner;
public class SearchDeletion2 {
private int a[] ;
SearchDeletion2(int size){
a =new int[size];
}
public void set(int index,int elem){
a[index]=elem;
}
public int get(int index){
return a[index];
}
public static void main(String[] args) {
SearchDeletion2 arr = new SearchDeletion2(100);
arr.set(0,33);
arr.set(1,22);
arr.set(2,11);
arr.set(3,99);
arr.set(4,66);
arr.set(5,44);
arr.set(6,77);
arr.set(7,88);
arr.set(8,55);
arr.set(9,112);
int i;
int l=10;
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
for(i=0;i<l;i++)
if(arr.get(i)==r)
break;
System.out.println(i);
for(int k =i;k<l;k++)
arr.set(k,arr.get(k+1));
l--;
System.out.println(l);
for (int o=0;o<l;o++)
System.out.println(arr.get(o));
}
}
The second piece of code is wrong, because at the last iteration (with k==l-1) it performs arr.get(k+1), which means arr.get(l-1+1), which is arr.get(l), which is an invalid index for an array of l elements (going from 0 to l-1).
The code doesn't break because the actual array is bigger than l (100 'slots' are allocated, against 10 actually used). Anyway, it isn't a code that is safe under all the possible circumstances. So you shouldn't use it.
PS: the code would actually be safe, if the get method was implemented to be somehow resilient to invalid indices. Such as:
public int get(int index){
return (index < size) ? a[index] : 0;
}
You are not increasing or decreasing the size of array at any point in this code. All you are doing is changing the variable l, which dictates how many elements you are going to traverse. So even if you changed the loop to for(int k =i;k<l+10;k++) it would behave in the same way unless you started accessing elements beyond the allocated 100 in which case you would get ArrayIndexOutOfBounds exception.
I want to take inputs from console and use the numbers in performing calculations. I want to stop receiving items into array when i receive some ref value like"10"(in this case) from console. As soon as i enter 10 in console the array has to be ended and the values in array have to be multiplied. I have tried this as a program but am getting 0 as answer for the product being performed.
public class Scrap {
private static int i;
private static double[] as;
public static void main(String[] args)
{
as=new double[100];
for(i=0;i<as.length;i++)
{
as[i]=dscan();
if(as[i]==10)
break;
}
double d=1;
for(i=0;i<as.length;i++)
{
d=d*as[i];
}
System.out.println("Product is :"+(d/10));
}
public static double dscan()
{
System.out.print(" : ");
return new Scanner(System.in).nextDouble();
}
}
In your case as=new double[100]; will initialize array with 100 zeros (default value for primitive double) and as.length will always return 100 (the size of initialized array) and not the number of valid elements, so if you enter less than 100 values the rest will remain zeros, which will be used for multiplication..
To make it work you either need to count the number of valid elements in a separate variable and then use it restrict your array window or as Matej sugests use a dynamically sized collection.
this code works ... i improved it to use List instead of array , because at start you dont know how many inputs you will have ... if you dont understand anything , just ask ...
public class Scrap {
private static int i;
private static ArrayList<Double> al = new ArrayList<Double>();
public static void main(String[] args) {
while (true) {
double d = dscan();
if (d != 10) {
al.add(d);
}else{
break;
}
}
double d = 1;
for (i = 0; i < al.size(); i++) {
d = d * al.get(i);
}
System.out.println("Product is :" + (d / 10));
}
public static double dscan() {
System.out.print(" : ");
return new Scanner(System.in).nextDouble();
}
}
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.
I am new to programming and Java as well. I need to write a void method which sorts the array entered, I have the code written but do not know how to display the sorted list from void method. Anyone willing to help. It will be greatly appreciated.
package util.assign4;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import util.IO;
public class UtilAssign4 {
public static int[] getData (String input){
StringTokenizer st = new StringTokenizer(input);
int []x = new int[st.countTokens()];
for(int i = 0;st.hasMoreTokens(); i++){
try{
x[i] = Integer.parseInt(st.nextToken());
}
catch(Exception e){
JOptionPane.showMessageDialog(null," Invalid input");
System.exit(1);
}
}
return x;
}
public static int getHighest(int g[]){
int hi = g[0];
for( int k = 1; k <g.length;k++)
if(g[k]> hi) hi = g[k];
return hi;
}
public static int getSmallest(int p[]){
int sm = p[0];
for(int l = 1;l<p.length;l++)
if(p[l] < sm) sm = p[l];
return sm;
}
public static float getAverage(int n[]){
float sum = 0.0f;
for(int y = 0;y <n.length; y++) sum += n[y];
return sum/n.length;
}
public static void getSorted(int grades []){
for(int i = 0; i<grades.length-1;i++){
int largest =i;
for(int j = 0;j<grades.length;j++)
if(grades[j]>grades[largest]) largest = j;
int temp = grades[largest];
grades[largest] = grades[i];
grades[i]=temp;
}
}
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enetr one or more grades:");
int [] x = getData(input);
int j = getHighest(x);
int m = getSmallest(x);
float a = getAverage(x);
IO.showMsg("Array you entered:" + input + String.format("\nThe"
+ " higheset grade is:%2d \n"
+ "The Lowest Grade is:%2d \n"+"The average is:%2.2f\n"
+ "The sorted list: ",
j,m,a));
}
}
You are not supposed to print the contents of the array in the sort method. Your requirement (I wager) is to sort the array supplied to the method 'in-place' (which it already looks like you are doing). What this means is that given an array:
int[] grades = new int[] {34, 76, 12, 0, -1};
That when you call:
UtilAssign4.getSorted(grades);
That the array passed into the method is actually sorted inside the method, and as such does not need to be returned (that's why your return type is void). So to summarize, before calling the sort method, your array is unsorted. After the call completes, tbe very same array has now been sorted.
So now you can then print out the sorted array in the calling method (in this case main(String[]):
getSorted(x); // <-- call the sort function, on your array
String msg = String.format("\nThe higheset grade is:%2d \n"
+ "The Lowest Grade is:%2d \nThe average is:%2.2f\n"
+ "The sorted list: %s", j, m, a, Arrays.toString(x));
IO.showMsg(msg);
Note the Arrays.toString(x)? That will take your sorted array, and convert it into a string representation (will look something like this: [76, 34, 12, 0, -1]).
in void method short your array in any field Array that is
public class UtilAssign4 {
private Integer[] shorted = new Integer[100];
public static int[] getData (String input){
.
.
}
and do your stuff with above array in your void method and use this where you want