How do I invoke a method with array parameter in java? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an assignment in which I have to perform operations on array in Java, I have to make separate functions of each operation, which I will write but I can not figure out how to invoke a method with array parametres. I usually program in c++ but this assignment is in java. If any of you can help me, I'd be really thankful. :)
public class HelloJava {
static void inpoot() {
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Please enter 10 numbers ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
}
static void outpoot(int[] numbers) {
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
public static void main(String[] args) {
inpoot();
outpoot(numbers); //can not find the symbol
}
}

Your inpoot method has to return the int[] array, and then you pass it to outpoot as a parameter:
public class HelloJava {
static int[] inpoot() { // this method has to return int[]
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Please enter 10 numbers ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
return numbers; // return array here
}
static void outpoot(int[] numbers) {
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
public static void main(String[] args) {
int[] numbers = inpoot(); // get the returned array
outpoot(numbers); // and pass it to outpoot
}
}

When you call outpoot it should be
outpoot (numbers);

Related

Return a randomly generated sorted Array as a String. HOW? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I'm trying to write a class that returns a String to the main method. The String is supposed to contain 6 randomly generated numbers from 1-99, and the numbers are supposed to be sorted before they are returned. However it doesn't work at all and I've been sitting all day trying to figure this out. I am new to Java and would prefer to just give it up but it's a class at my university. The code looks like this:
package lab1;
import java.util.Random;
import java.util.Scanner;
public class Lab111 {
private String rad;
public String getLottorad() {
Random r = new Random();
int[] tal = new int[6];
for (int i = 0; i < 6; i++) {//generating 6 numbers
tal[i] = r.nextInt(99)+1;
}
int i,j,crap;
for(i=0;i<100;i++) //trying to sort the generated numbers
for(j=i+1;j<100;j++)
if(tal[i]>tal[j])
{
crap=tal[i];
tal[i]=tal[j];
tal[j]=crap;
}
rad = String.valueOf(tal[i]); /*trying to turn the sorted numbers into an int*/
return rad;
}
public static void main(String[] args) {
System.out.print("How many lottery lines do you want? :");
Scanner tgb = new Scanner(System.in);
int antal = tgb.nextInt();
Lab111 l = new Lab111();
for (int i = 0; i < antal; i++)
System.out.println(l.getLottorad()); // printing the sorted strings
}
}
If someone could explain what I'm doing wrong it would be really appreciated. Me and a classmate that is on my level have been tearing our hair off all day.
You might have to change your code as below.
private String rad;
public String getLottorad() {
Random r = new Random();
int[] vek = new int[10];
for (int i = 0; i < 10; i++) {
vek[i] = r.nextInt(22);
rad = String.valueOf(vek[i]);
}
return rad;
}
public static void main(String[] args) {
System.out.print("How many lottery lines do you want? :");
Scanner tgb = new Scanner(System.in);
int antal = tgb.nextInt();
Lab111 l = new Lab111();
for (int i = 0; i < antal; i++)
System.out.println(l.getLottorad());
}

How to solve "Cannot Make Static Reference to Non-Static Method" in a Java mastermind game? [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 7 years ago.
This question is based on my former question. How to add a "cheat" function to a Java mastermind game
I added the cheat function to my program, but it cannot compile because of "Cannot Make Static Reference to Non-Static Method"(the old codes works, you can check it through the link I post). Here are my new codes:
import java.util.*;
public class mm {
static int[] random;
public static void main(String[] args) {
System.out.println("I'm thinking of a 4 digit code.");
//update
mm m1 = new mm();
random = m1.numberGenerator();
int exact=0, close=0;
while(exact!=4){
int[] guess= m1.userinput(); //update
exact=0;
close=0;
for(int i=0;i<guess.length;i++){
if(guess[i]==random[i]){
exact++;
}
else if (random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]) {
close++;
}
}
if(exact==4){
System.out.println("YOU GOT IT!");
}
else{
System.out.println("Exact: "+exact+" Close: "+close);
}
}
}
public int[] userinput() {
System.out.print("Your guess: ");
Scanner user = new Scanner(System.in);
String input = user.nextLine();
//cheater
if (input.equals("*")) {
System.out.format("Cheater!Secret code is:");
for(int i=0;i<random.length;i++){
System.out.print(random[i]);
}
}
int[] guess = new int[4];
for (int i = 0; i < 4; i++) {
guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
}
return guess;
}
public int[] numberGenerator() {
Random rnd = new Random();
int[] randArray = {10,10,10,10};
for(int i=0;i<randArray.length;i++){
int temp = rnd.nextInt(9);
while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
temp=rnd.nextInt(9);
}
randArray[i]=temp;
}
return randArray;
}
}
How to solve this?
You can't call a non-static method directly from a static method. in public static main(String [] args)
To do so, you should first create an object of the class.
try this at main method:
mm m1 = new mm();
random = m1.numberGenerator();
int [] guess = m1.userInput();
this should work
The other option would be to make userinput method static as well

Generating non-repeating random numbers in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to generate non-repeating random numbers. Please help me identify the problem in my code and how to fix it.
package number;
public class name {
public static void main(String[] args)
{
int counter=0;
boolean flag=true;
int number=0;
int a[] = new int[16];
try
{
while(counter<16)
{
while(flag)
{
number = (int)(Math.random()*16);
for(int i = 0; i < 16; i++)
if(a[i]==number)
{
continue;
}
else
{
System.out.println(""+i+ "===="+ number);
a[counter]=number;
flag= false;
}
}
for(int i1=0;i1<16;i1++)
{
for(int j=0;j<16;j++)
{
if(a[i1]==a[j])
{
}
else
System.out.print(" \t "+a[i1]);
}
}
}
counter --;
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
You're changing the counter variable outside the while(counter<16) loop and you should increment counter counter++ instead of decrementing it.

java generics: defining objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to learn Java and having trouble understanding generics. I'm attempting to define an object of Integer data type, then use the object to to call a generic method.
Guided by the API and some web resources, I've been trying all sorts of things but I don't know if i'm on the right track in terms of simply defining the object.
SearchSortAlgorithms.java:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
public void quickSort(T[] list, int length)
{
recQuickSort(list, 0, length - 1);
}
}
TestQuickSort.java
public class TestQuickSort
{
static void main(String [] args)
{
// define an Integer array of 50000 elements
Integer[] anArray = new Integer[5000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*50000)
for (int i = 0; i < anArray.length; i++) {
anArray[i] = (int)(Math.random() * i);
}
// define an object of SearchSortAlgorithm with Integer data type
// use this object to call the quickSort method with parameters: your array name and size-50000
Integer aSortedArray = new Integer(5000);
public void quickSort(anArray, 5000) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return aSortedArray.quickSort(anArray, 5000);
}
// print out the first 50 array elements with a for loop
// they have to be sorted now
for (int k = 0; k <= 50; k++) {
System.out.print(aSortedArray[k] + " ");
}
}
}
Errors on these lines:
public int TestQuickSort () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
-Illegal start of expression: I wonder if my attempt at creating the constructor is right
-; expected
Ignoring any other potential errors in your code (or due to its presentation to us here), you are attempting to declare another method in main.
public int SearchSortAlgorithm () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
This needs to be moved out of main. And also fixed to actually return an int. And main's signature should be public static void main(String[] args).
Although, it should really be returning an int[] instead...
public static int[] searchSortAlgorithm (final int[] anArray) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return quickSort(anArray, 5000);
}
...and called in your main method like this...
int[] aSortedArray = searchSortAlgorithm(anArray);
for (int k = 0; k <= 50; k++) { // would be better to use aSortedArray.length
System.out.print(aSortedArray[k] + " ");
}

How can i resolve the Exception in thread "main" java.lang.ArrayndexOutOfBoundsException [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm Java beginner, I have taken piece of code from online and trying the program on permutation. Im getting error as
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1.
Can anybody help to resolve this problem. Thank you.
// Permute.java -- A class generating all permutations
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Permute implements Iterator {
private final int size;
private final Object [] elements; // copy of original 0 .. size-1
private final Object ar; // array for output, 0 .. size-1
private final int [] permutation; // perm of nums 1..size, perm[0]=0
private boolean next = true;
// int[], double[] array won't work :-(
public Permute (Object [] e) {
size = e.length;
elements = new Object [size]; // not suitable for primitives
System.arraycopy (e, 0, elements, 0, size);
ar = Array.newInstance (e.getClass().getComponentType(), size);
System.arraycopy (e, 0, ar, 0, size);
permutation = new int [size+1];
for (int i=0; i<size+1; i++) {
permutation [i]=i;
}
}
private void formNextPermutation () {
for (int i=0; i<size; i++) {
// i+1 because perm[0] always = 0
// perm[]-1 because the numbers 1..size are being permuted
Array.set (ar, i, elements[permutation[i+1]-1]);
}
}
public boolean hasNext() {
return next;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private void swap (final int i, final int j) {
final int x = permutation[i];
permutation[i] = permutation [j];
permutation[j] = x;
}
// does not throw NoSuchElement; it wraps around!
public Object next() throws NoSuchElementException {
formNextPermutation (); // copy original elements
int i = size-1;
while (permutation[i]>permutation[i+1])
i--;
if (i==0) {
next = false;
for (int j=0; j<size+1; j++) {
permutation [j]=j;
}
return ar;
}
int j = size;
while (permutation[i]>permutation[j]) j--;
swap (i,j);
int r = size;
int s = i+1;
while (r>s) { swap(r,s); r--; s++; }
return ar;
}
public String toString () {
final int n = Array.getLength(ar);
final StringBuffer sb = new StringBuffer ("[");
for (int j=0; j<n; j++) {
sb.append (Array.get(ar,j).toString());
if (j<n-1) sb.append (",");
}
sb.append("]");
return new String (sb);
}
public static void main (String [] args) {
for (Iterator i = new Permute(args); i.hasNext(); ) {
final String [] a = (String []) i.next();
System.out.println (i);
}
}
}
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
As you have not posted any stack trace. Problem is unclear. But these links may help you.
oracle docs
stackoverflow

Categories

Resources