I am unclear as to what this is asking me to do, and how I execute it, in reference to the int [] copyAndReplaceLessThan(int []a, int b) method. Any help would be greatly appreciated, thanks.
Task:
Test this method in main. Print both the original array and the returned array which the method, copyAndReplaceLessThan, returns. Since this method returns a value (an integer array), you need to “catch” the returned value in a local variable (of type int []) in the calling method (main).
For example: Assuming you pass the array “x” to the method and use array “y” to catch the returned value. Print x before you call the method and then print both x and y after calling the method.
public class ArrayExamples{
public static void swapInts(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
}
public static void swapIntArrays(int [] a, int [] b){
int x;
for (int i=0; i<a.length; i++){
x = a[i];
a[i]=b[i];
b[i]=x;
}
}
public static void printArray(int[] a){
for(int i = 0; i < a.length; i++)
{
System.out.print(a[i] + " ");
}
System.out.println("");
}
public static void main(String args[]){
int [] one ={3,4};
int [] two ={7,8};
printArray(one);
printArray(two);
swapIntArrays(one,two);
printArray(one);
printArray(two);
System.out.println();
int [] x ={3,45,17,2,-1,44,9,23,67,2,-6,-23,-100,12,5,1212};
int b = 12;
printArray(x);
replaceLessThan(x,b);
printArray(x);
printArray(x);
copyAndReplaceLessThan(x,b);
printArray(x);
printArray(y);
}
public static void replaceLessThan(int []a, int b){
for(int i=0; i < a.length; i++){
if(a[i] < b){
a[i] = b;
}
else{
a[i] = a[i];
}
}
}
public static int[] copyAndReplaceLessThan(int []a, int b){
int []x = a;
int[]y = x;
for(int i=0; i < a.length; i++){
if(a[i] < b){
a[i] = b;
y[i] = b;
}
else{
a[i] = a[i];
y[i] = a[i];
}
}
return y;
}
}
public static int[] copyAndReplaceLessThan(int[] a, int b)
{
int[] x = a.clone();
for (int i = 0; i < x.length; i++)
{
if (x[i] < b)
{
x[i] = b;
}
}
return x;
}
Some problems:
You're supposed to leave the original array unaltered, yet you're setting its elements with
a[i] = b;
And there's no point to doing this
a[i] = a[i];
as you're just resetting the value to itself.
But your biggest problem is that you're not creating a new array, as you're supposed to. Instead, your "new" array (y) is referring to the original one (a), and therefore any changes to y are actually being made in the original.
I also recommend that you either test or try a for nullness.
Related
There's an error in this code:
ArraySortSearch.java:12: error: incompatible types: int cannot be
converted to int[]
int [] mySorted = sort(myNumbers);
^ ArraySortSearch.java:56: error: incompatible types: int[] cannot be converted to int
return a;
I just started learning Java not long ago. This is so difficult:( How do I solve this?
//not allowed to use import java.util
public class ArraySortSearch { // shouldn't be changed from here
public static void main(String[] args) {
int [] myNumbers = {15,12,23,0,10,55,2,78,9,6,1,4,11};
System.out.println("Looking for numer 55: ");
System.out.println(find(myNumbers,55));
System.out.println("Sorted Array:");
int [] mySorted = sort(myNumbers);
for(int i = 0; i< mySorted.length; i++) {
System.out.println(mySorted[i]);
}
} //to here
public static int find(int [] a, int number){ //this method works
for(int i=0; i<a.length; i++){
if(a[i]==number){
return i;
}
else{
continue;
}
}
return -1;
}
public static int sort(int [] a){ //this method is the problem
for(int b=0; b<a.length; b++){
for(int i =1; i<a.length; i++){
if(a[b]<a[i]){
int temp = a[b];
a[b] = a[i];
a[i] = temp;
}
}
}
return a;
}
}
Thank you in advance!
Your return type is an int but a is an array. Since you are sorting the array in place, just have a return type of void and no need to return anything.
Also, make your outer loop go to a.length-1 and have your inner loop start at b+1.
Here I am Getting an ERROR
Cannot make a static reference to the non-static method leftRotatebyOne(int[], int) from the type LeftRotation
Here is my code..
public static int[] arrayLeftRotation(int[] arr, int n, int k)
{
int i;
for (i = 0; i < k; i++)
leftRotatebyOne(arr, n);
}
void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++)
{
a[a_i] = in.nextInt();
}
int[] output = new int[n];
output = arrayLeftRotation(a, n, k);
for(int i = 0; i < n; i++)
System.out.print(output[i] + " ");
}
Can anybody tell to proceed me further.
In the main method you are calling arrayLeftRotation method (which is static) which in turn is calling leftRotatebyOne, here leftRotatebyOne is non-static method, which is being called through a static method which is not allowed in java.
Change the declaration of the method leftRotatebyOne to static as follows
static void leftRotatebyOne(int arr[], int n)
So the purpose of this program is to selectively sort a random array of integers form largest to smallest. To do this, I needed to keep swapping the first element with the largest element. I think my methods are correct, but I am fairly new to Java and not sure what to call in main in order to execute my methods correctly. Thank you in advance!
package sortarray;
public class SortArray {
public static int randomInt(int low, int high) {
double e;
double x=Math.random();
e=low+x*(high-low);
return (int)e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}
return a;
}
public static int indexOfMaxInRange(int[] a, int low, int high) {
int index = low;
for (int i = low + 1; i < a.length; i++) {
if (a[i] > a[index]) {
index = i;
}
}
return index;
}
public static void swapElement(int[] a, int index1, int index2) {
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
public static void sort(int[] a) {
int length = a.length;
//use length-1 because do not need to swap last element with itself
for (int i = 0; i < length-1; i++) {
int indexOfMax = indexOfMaxInRange(a, i, length-1);
swapElement(a, i, indexOfMax);
}
}
public static void printArray(int[] a) {
for(int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}
public static void main(String[] args) {
int[] array = randomIntArray(30);
printArray();
}
}
To sort the array, you simply need to call the following:
sort(array);
Then, you can print the array again to verify that it is sorted with:
printArray(array);
Also you can call the method sort() within of printArray() method, so when you call printArray() it will print sorted:
...
public static void printArray(int[] a) {
sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}
public static void main(String[] args) {
int[] array = randomIntArray(30);
printArray(array);
}
...
Here is my code that I posted on Code Review. This sort an array of String, But you can put integer instead.
https://codereview.stackexchange.com/questions/160243/sort-a-given-string-in-ascending-order
Given string
[H, B, D, G, F, E, A, C]
Output
[A, B, C, D, E, F, G, H]
public class sortArray {
public static void sort (String[] str)
{
int lastPos = str.length - 1;
int minPos = 0;
String s = "";
for (int i = 0; i < lastPos; i++)
{
minPos = i;
for (int j = i + 1; j <= lastPos; j++)
if (str[j].compareTo (str[minPos]) < 0)
minPos = j;
if (minPos != i)
{
s = str[i];
str[i] = str[minPos];
str[minPos] = s;
}
}
}
public static void main(String[] args){
String[] str = {"H", "B", "D", "G","F", "E", "A", "C"};
sort(str);
System.out.println(Arrays.toString(str));
}
}
There must have the arguments in the methods you use,
you should put the array in the ( )
you can use inbuilt function of Arrays. Simply call the inbuilt method and pass your array.
Arrays.sort(pass your array here).
If you dot want to use inbuilt method please refer this link.
Java : Sort integer array without using Arrays.sort()
that is the error I get when trying to write out the Selection sort. Could someone point out what I'm doing wrong. My code is below. Thanks!
public class Selection
{
static void sort(Comparable[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
int min = i;
for (int j = i+1; j < N; j++)
if (less(a[j], a[min]))
min = j;
exch(a, i, min);
}
}
private static boolean less(Comparable v, Comparable w)
{
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a, int i, int j)
{
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String args[])
{
int[] ys = {3,4,5,5,22,4,66,4444,33,3,656,544,4};
Selection.sort(ys);
}
}
int is a primitive type, and therefore cannot implement any interface. That's why int[] cannot be passed to a method that expects Comparable[].
You could overcome this error by changing ys to be an array of Integer (i.e Integer[]), since Integer implements Comparable.
int is a primitive data type. It is not a class, and it doesn't implement Comparable
You should use Integer instead, which does implement Comparable.
Comparable works with objects, and as you know an int is not an object. int[] resolves to a singular object not an array of objects.
If you define ys as Integer[] then you will get your expected Array of objects.
As mentioned by earlier asnwers, you can't apply int for Comparable, but if you still want to work with primitives and use Integer instead of Comparable which implements Comparable and the compiler will implicitly convert int to Integer:
static void sort(int[] a)
{
int N = a.length;
for (int i = 0; i < N; i++)
{
int min = i;
for (int j = i+1; j < N; j++)
if (less(a[j], a[min]))
min = j;
exch(a, i, min);
}
}
private static boolean less(Integer v, Integer w)
{
return v.compareTo(w) < 0;
}
private static void exch(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
My code compiles fine, but when I run it I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Sudoku.(Sudoku.java:20) at Test.main(Test.java:7)
The code is as follows:
Main Test class:
public class Test {
public static void main(String[] args) {
Sudoku puzzle;
int[][] entries = {{1,0,0,0},{0,0,0,3},{0,0,4,0},{0,4,0,0}};
puzzle = new Sudoku(2,2,entries);
boolean somethingChanged=true;
while(somethingChanged) {
somethingChanged=false;
System.out.println(puzzle);
for (int i=0; i<puzzle.size; i++)
for(int j=0; j<puzzle.size; j++)
if(puzzle.oneOption(i, j)!=puzzle.EMPTY) {
// exactly one value can be filled in at location i,j
// do this now, and record that something has changed
// compared to the previous iteration of the while loop
puzzle.setValue(i,j,puzzle.oneOption(i,j));
somethingChanged=true;
}
}
// if oneOption is implemented correctly, the puzzle is now solved!
System.out.println(puzzle);
}
}
and my uncommented Sudoku Class:
class Sudoku {
int cellHeight, cellWidth, size,EMPTY = 0;
int [][] sudGrid = new int[cellHeight * cellWidth][cellHeight * cellWidth];
int [][] cellGrid = new int [cellHeight][cellWidth];
public Sudoku(int a, int b){
cellHeight = a;
cellWidth = b;
size = cellHeight*cellWidth;
}
public Sudoku(int a, int b, int array[][]){
cellHeight = a;
cellWidth = b;
size = cellHeight*cellWidth;
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
int temp = array[i][j];
sudGrid[i][j] = temp;
}
}
}
public Sudoku(){
cellHeight = 3;
cellWidth = 3;
size = cellHeight*cellWidth;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
sudGrid[i][j] = 0;
}
public void setValue(int r,int c, int v){
sudGrid[r][c] = v;
}
public int getValue(int r, int c){
return sudGrid[r][c];
}
public void clear(int r, int c){
sudGrid[r][c] = EMPTY;
}
public String toString(){
String message = "";
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
message = message + sudGrid[i][j];
if (j == cellWidth){
message = message + " ";
}
}
message = message + "\n";
}
return message;
}
public int oneOption(int r, int c){
return 1;
}
}
Sorry, I know this is a lot of code to splat on the screen, but I haven't done a lot on arrays, let alone two dimensional. I know my oneOption() method at the moment does nothing, I just needed it to compile, but where the errors are, is
int temp = array[i][j];
sudGrid[i][j] = temp;
and
int[][] entries = {{1,0,0,0},{0,0,0,3},{0,0,4,0},{0,4,0,0}};
puzzle = new Sudoku(2,2,entries);
Now I assumed where the entries array is declared is correct as this is code that my lecturer has set up for us, and we are only designing the Sudoku class. and I was trying to make the values of the entries array, go into the sudGrid array, I assumed I did it correctly, but im getting the exception error,
any ideas?
Your subgrid is defined as a zero length two dimensional array, so you can't fit anything in there.
See here:
int cellHeight, cellWidth, size,EMPTY = 0;
int [][] sudGrid = new int[cellHeight * cellWidth][cellHeight * cellWidth];
cellHeight and cellWidth are initialized to zero by default, then you create a new int[0*0][0*0] array.
Change your constructor to the following:
public Sudoku(int a, int b, int array[][]){
cellHeight = a; // Changing these two instance variables will *NOT*
cellWidth = b; // retrofit your subGrid to a new size.
size = cellHeight*cellWidth;
subGrid = new int[size][size];
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
int temp = array[i][j];
sudGrid[i][j] = temp;
}
}
}
You're setting your Sudoku.size to be the entire number of cells in the puzzle, and then trying to read that many rows and columns. You need to iterate just to the number of columns and rows.