I get this error and I don't know what to do, please can some one tell me a good answer.
import java.util.*;
public class test{
public static int expand(int[] a,int n){
if (n==1)
return a;
if (n<=0)
return new int[0];
if(n<1)
int []c=new int[a.length*n];
for(int i=0;i<a.length;i++){
int num=a[i]/n;
for(int j=0;j<n;j++){
c[i*n+j]=num;
}
}
return c;
}
public static void main (String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("please enter the n number:");
int x=sc.nextInt();
System.out.println("please enter the size of array:");
int arr=sc.nextInt();
int []b=new int [arr];
for(int o=0;o<b.legnth;o++){
System.out.println("please enter the"+o+"number:");
b[o]=sc.nextInt();
}
System.out.println("Java tester"+b);
System.out.println("expanded form is"+expand(b,x));
}
}
I get this error:
variable declaration not allowed here
why though?
i dont think I can remove identifying it as an integer or else it wont work
The reason is that you are trying to declare an object in an if else scope but no are using curly braces { }
Change the code to:
if (n < 1) {
int[] c = new int[a.length * n];
}
Or declare int []c = new int [a.length] at the top of the function and assing without declaration
c = new int[a.length*n];
public static int[] expand(int[] a,int n){
int [] c = null;
if (n==1)
return a;
if (n<=0)
return new int[0];
if(n<1){
c = new int[a.length*n];
for(int i=0;i<a.length;i++){
int num=a[i]/n;
for(int j=0;j<n;j++){
c[i*n+j]=num;
}
}
}
return c;
}
I think what you wanted to achieve:
public static int[] expand(int[] a,int n) {
if (n==1)
return a;
if (n<=0)
return new int[0];
int []c =new int[0];
if(n<1) {
c = new int[a.length * n];
for (int i = 0; i < a.length; i++) {
int num = a[i] / n;
for (int j = 0; j < n; j++) {
c[i * n + j] = num;
}
}
}
return c;
}
errors in your code were related to incorrect return type(int instead of int[]), c out of scope in for-loop.
Related
I'm trying to make my personal sudoku generator in Java, but I have a problem with setter element method of the matrix.
Field Class:
public void setField(int [][] field){
this.field = Arrays.copyOf(field, field.length);
}
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
//Change the element of the field
public void setElement (int i, int j, int n) {
getField()[i][j] = n;
setField(getField());
}
Main:
// First Print
for (i = 0; i < field.getField().length; i++) {
System.out.println();
for (j = 0; j < field.getField()[i].length; j++)
System.out.print(field.getField()[i][j]);
}
System.out.println();
System.out.println("Select Row");
i = input.nextInt();
System.out.println("Select Column");
j = input.nextInt();
System.out.println("Put Number");
n = input.nextInt();
field.setElement(i,j,n);
// Second Print
for (i = 0; i < field.getField().length; i++){
System.out.println();
for (j = 0; j < field.getField()[i].length; j++)
System.out.print( field.getField()[i][j]);
}
I don't know why the second print is the same as the first one.
You are creating copies of the matrix in the setField and getField methods
public void setField(int [][] field){
this.field = Arrays.copyOf(field, field.length);
}
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
Doing that in the method setElement you:
get a copy of the original matrix.
change an element of the copy
set a copy of the original matrix
Here your code with comments explaining each step:
public void setElement (int i, int j, int n) {
// 1 - Get a copy of the original matrix
getField()
// 2 - Change an element of the copy
[i][j] = n;
// 3.a - get a copy of the original matrix
// 3.b - Set the copy
setField(getField());
}
So the final effect doesn't change the original matrix.
You can have the desired result doing the following:
public void setField(int [][] field){
this.field = field;
}
public int[][] getField() {
return field;
}
//Change the element of the field
public void setElement (int i, int j, int n) {
field[i][j] = n;
}
// you do a copy of internal array
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
// and then chane element of this copy
public void setElement (int i, int j, int n) {
getField()[i][j] = n;
setField(getField());
}
I ran your program. It is running ok. But, in the beginning, I was getting null pointer exception error. So, maybe you should consider changing following things:
Add private int[][] field = new int[3][3]; in MyBean class.
the main() method:
public static void main(String[] args) {
MyBean myBean = new MyBean();
myBean.setElement(0, 0, 113);
myBean.setElement(0, 1, 114);
myBean.setElement(0, 2, 115);
int i1,j1,n;
Scanner input = new Scanner(System.in);
//First Print
for (int i = 0; i < myBean.getField().length; i++) {
System.out.println();
for (int j = 0; j < myBean.getField()[i].length; j++)
System.out.print(myBean.getField()[i][j]);
}
System.out.println();
System.out.println("Select Row");
i1 = input.nextInt();
System.out.println("Select Column");
j1 = input.nextInt();
System.out.println("Put Number");
n = input.nextInt();
myBean.setElement(i1,j1,n);
//Second Print
for (int i = 0; i < myBean.getField().length; i++){
System.out.println();
for (int j = 0; j < myBean.getField()[i].length; j++)
System.out.print( myBean.getField()[i][j]);
}
input.close();
}
first time post here.
I am trying to create a class which compares quick sort, merge sort, bubble sort, and selection sort. I have implemented all of the sort methods and created a random array method which populates a random array with 1000 random ints. However when I run my program my main method stops after the initial welcome message and allows for user input. Any help would be greatly appreciated, I'm sure its some simple mistake I am missing.
import java.util.Random;
public class TestSort {
private static int selectCount;
private static int bubbleCount;
private static int mergeCount;
private static int quickCount;
public static void main(String[] args){
System.out.println("Welcome to the search tester. "
+ "We are going to see which algorithm performs the best out of 20 tests");
int testSelection = 0;
int testBubble = 0;
int testQuick = 0;
int testMerge = 0;
//Check tests
int[] a = new int[1000];
populateArray(a);
int[] select = a;
int[] bubble = a;
int[] quick = a;
int[] merge = a;
testSelection = selectionSort(select);
testBubble = bubbleSort(bubble);
testQuick = quickSort(quick,0,0);
testMerge = mergeSort(merge);
System.out.println("Selection sort number of checks: " + testSelection);
System.out.println("Bubble sort number of checks: " + testBubble);
System.out.println("Quick sort number of checks: " + testQuick);
System.out.println("Merge sort number of checks: " + testMerge);
System.out.println("");
}
public static int[] populateArray(int[] a)
{
Random r = new Random();
a = new int[1000];
for(int i=0; i < a.length; i++)
{
int num = r.nextInt(1000);
a[i] = num;
}
return a;
}
//Sorting methods
public static int selectionSort(int[] a)
{
for (int i = 0; i < a.length; i++)
{
int smallestIndex = i;
for (int j=i; j<a.length; j++)
{
if(a[j]<a[smallestIndex])
{
smallestIndex = j;
}
}
if(smallestIndex != i) //Swap
{
int temp = a[i];
a[i] = a[smallestIndex];
a[smallestIndex] = temp;
selectCount++;
}
}
return selectCount;
}
public static int bubbleSort (int[] a)
{
boolean hasSwapped = true;
while (hasSwapped == true)
{
hasSwapped = true;
for(int i = 0; i<a.length-1; i++)
{
if(a[i] > a[i+1]) //Needs to swap
{
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
hasSwapped = true;
bubbleCount++;
}
}
}
return bubbleCount;
}
public static int mergeSort(int [] a)
{
int size = a.length;
if(size<2)//recursive halting point
{
return 0;
}
int mid = size/2;
int leftSize = mid;
int rightSize = size-mid;
int [] left = new int[leftSize];
int [] right = new int[rightSize];
for(int i = 0; i<mid; i++)
{
mergeCount++;
left[i] = a[i];
}
for(int i = mid; i<size; i++)
{
mergeCount++;
right[i-mid]=a[i];
}
mergeSort(left);
mergeSort(right);
//merge
merge(left,right,a);
return mergeCount;
}
private static void merge(int [] left, int [] right, int [] a)
{
int leftSize = left.length;
int rightSize = right.length;
int i = 0;//index of the left array
int j = 0; //index of right array
int k = 0; //index of the sorted array [a]
while(i<leftSize && j<rightSize)
{
if(left[i]<=right[j])
{
a[k] = left[i];
i++;
k++;
}
else
{
a[k] = right[j];
j++;
k++;
}
}
while(i<leftSize)
{
a[k] =left[i];
i++;
k++;
}
while(j<rightSize)
{
a[k] =right[j];
j++;
k++;
}
}
public static int quickSort(int[] a, int left, int right)
{
//partition, where pivot is picked
int index = partition(a,left,right);
if(left<index-1)//Still elements on left to be sorted
quickSort(a,left,index-1);
if(index<right) //Still elements on right to be sorted
quickSort(a,index+1,right);
quickCount++;
return quickCount;
}
private static int partition(int[] a, int left, int right)
{
int i = left;
int j = right; //Left and right are indexes
int pivot = a[(left+right/2)]; //Midpoint, pivot
while(i<j)
{
while(a[i]<pivot)
{
i++;
}
while(a[j]>pivot)
{
j--;
}
if(i<=j) //Swap
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
return i;
}
}
Your infinite loop is in bubbleSort:
public static int bubbleSort(int[] a)
{
boolean hasSwapped = true;
while (hasSwapped == true)
{
hasSwapped = false; // Need to set this to false
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1]) // Needs to swap
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
hasSwapped = true;
bubbleCount++;
}
}
}
return bubbleCount;
}
The problem is in your bubbleSort() method. The hasSwapped boolean is never set to false, so the while loops infinite times.
There is another problem in your code. In the main method, you will have to assign the array that the populateArray() method returns back to a. And the such assignments as int[] select = a; you do in the main method do not do what you want to do. Instead, just send the array a to your sorting methods.
Like this:
int[] a = new int[1000];
a=populateArray(a);
testSelection = selectionSort(a);
testBubble = bubbleSort(a);
testQuick = quickSort(a,0,0);
testMerge = mergeSort(a);
Could anyone help me out with this error?
I couldn't rectify this code.
I can't understand the error.
import java.io.*;
import java.util.Scanner;
public class findMax{
public static int findMax(int[] arr){
int max = 0;
for (int i = 1; i < value.length; i++){
if (value[i] > max){
max = value[i];
}
}
return max;
}
public static void main(String[] args){
int value[];
Scanner in = new Scanner(System.in);
value = in.nextInt();
findMax(value);
}
}
In the function findMax, you need to be consistent with your array variable name (you're currently passing int[] arr but accessing value). Also, you don't want to default max to 0 (you could use arr[0]). Something like,
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
Next, you need to instantiate and assign values into your array (and do something with the result of findMax as is the result isn't used). There are a few ways to do that. One might be,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] value = new int[] { in.nextInt() };
int max = findMax(value);
System.out.printf("The max value in %s is %d.%n", Arrays.toString(value), max);
}
Alternatively, you could create the array like
int[] value = new int[1];
value[0] = in.nextInt();
Also, you could eliminate the if if you use Math.max(int, int) in findMax like
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
max = Math.max(max, arr[i]);
}
return max;
}
import java.util.ArrayList;
import java.util.Scanner;
public class Stack{ public static int findMax(ArrayList<Integer> arr){
int max = 0;
for (int i = 1; i < arr.size(); i++){
if (arr.get(i) > max){
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args){;
Scanner in = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (in.hasNextInt()) {
value.add(in.nextInt());
}
System.out.println(findMax(value));
}}
Try this
public static int findMax(ArrayList<Integer> arr){
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++){
if (arr.get(i) > max){
max = arr.get(i);
}
}
return max;
}
public static void main(String[] args){;
Scanner in = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (in.hasNextInt()) {
value.add(in.nextInt());
}
System.out.println(findMax(value));
}
Main class:
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.println("Enter no. of elements you want in array:");
n = s.nextInt();
while(n!=69)
{
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
int[]odds;
OddsAndEvens s1 = new OddsAndEvens();
odds = s1.getAllOdds();
System.out.print("Odds- ");
System.out.print( Arrays.toString(odds));
System.out.println(" ");
System.out.println("");
System.out.println("Evens- ");
System.out.println(" ");
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
}
}
}
Secondary Class:
public class OddsAndEvens
{
private static int countEm(int[] a, int n,boolean odd,int count, int anticount)
{
for(int i = 0 ; i < n ; i++)
{
if(a[i] % 2 != 0)
{
count++;
}
anticount++;
}
return 0;
}
public static int[] getAllEvens(int[] a,int anticount,int n)
{
int[]gotevens = new int[anticount];
for(int i = 0 ; i < n ; i++)
{
int toc = 0;
if(a[i] % 2 == 0)
{
int a2 = a[i];
gotevens[toc] = a2;
toc++;
}
}
return gotevens;
}
public static int[] getAllOdds(int[] a,int count,int n)
{
int[]gotodds = new int[count];
for(int i = 0 ; i < n ; i++)
{
int tic = 0;
if(a[i] % 2 != 0)
{
int a1 = a[i];
gotodds[tic] = a1;
tic++;
}
}
return gotodds;
}
}
I keep getting the following error.
G:\MyProjects\Arraysoddsevens\OddsAndEvensRunner.java:33: error: method getAllOdds in class OddsAndEvens cannot be applied to given types; odds = s1.getAllOdds();
^
required:int[],int,int
found: no arguments reason: actual and formal argument lists differ in length 1 error
I've been googling for a solution with no luck.
To call this method getAllOdds() you need 3 parameters see this:
public static int[] getAllOdds(int[] a,int count,int n){...
Basically I need to call my "sum" and "sumOfEvens" methods into the main method. The "sum" method is for when the array contains the lucky numbers as seen in the "isLucky" method. The "sumOfEvens" method adds of the even numbers if the array doesn't contain a lucky number.
So "sum" = true
and "sumOfEvens" = false
So here is my code...
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
boolean b = isLucky(a);
int result;
if(b)
result = sum(a);
else
result = sumOfEvens(a);
You can do it in one line:
int result = isLucky(a) ? sum(a) : sumOfEvens(a);