Program continues to run after method is finished - java

I have made a simple program, with two classes. The method works fine, however it continues to run after completing my method resulting in this being seen in the output and I have no idea why:

Your myArrayOne method calls itself. That's the problem with infinite recursion.
public static int myArrayOne() {
// that's the problem
return myArrayOne();
}
That is probably what are you trying to accomplish:
// void --> List<Integer>
// static
public List<Integer> myArrayOne() {
ArrayList<Integer> packOfCards = new ArrayList<Integer>();
Random rand = new Random();
for (int j = 0; j<5; j++)
{
pick = rand.nextInt(10);
packOfCards.add(pick);
}
// myArrayOne(); --> packOfCards
return packOfCards;
}
public static void main(String[] args) {
myattributes attributes = new myattributes();
List<Integer> values = attributes.myArrayOne();
}

Related

How to display Fibonacci numbers using a Linked list in Java

I have created a class using linked list to display 20 Fibonacci numbers. Here is my code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList(LinkedList<Integer> FibonacciLinkList) {
this.fibonacciList = FibonacciLinkList;
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
LinkedList fibonacciList = new LinkedList();
fibonacciList.display(); //This is where the error is
}
}
The problem I am having is displaying the Fibonacci numbers on the console.
I have tried to do this by using a display method but it hasn't really worked for me. I have done a lot of searching online and on SO and have tried them but they have not worked for me. It would be appreciated if you could fix my code so that it does work.
I am new to linked list and this is the first time I am coding a linked list myself and I feel that a solution to this problem will help me understand linked lists better.
As I mentioned, LinkedList is not an instance of FibonacciLinkedList, and it does not possess the display() method. Attempting to invoke it on the LinkedList object will lead to failure to compile.
The sum() method is not invoked nor does it actually do anything. That is, it does not assign anything to the fibonacciList you have.
I would recommend that you extend the LinkedList class and generate the items on instantiation. Then, using the default toString() you can display to console. After all, the class is simply an extension of the LinkedList data structure to store Fibonacci numbers up to 20.
As you extend LinkedList, you inherit the AbstractCollection.toString() method for which the "string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]")."
public class FibonacciLinkedList extends LinkedList<Integer> {
public FibonacciLinkedList(int n){
int a = 0, b = 0, c = 1;
for(int i = 1; i <= n; i++) {
a = b;
b = c;
c = a + b;
this.add(c);
}
}
public void display() {
System.out.println(this.toString());
}
public static void main(String[] args) {
FibonacciLinkedList list = new FibonacciLinkedList(20);
list.display();
}
}
I fixed your code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList() {
this.fibonacciList = new LinkedList<Integer>();
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
fibonacciList.add(a);
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
FibonacciLinkList fibonacciList = new FibonacciLinkList();
fibonacciList.sum();
fibonacciList.display();
}
}
Try this.
There is several points that you need to take care :
sum() is never called.
the look in sum() does not change fibonacciList, it only uses local variables and does nothing else with it.
display() is NOT a LinkedList function, so it will likely not work. And even if it were working, it will likely not display what you expect : you need to loop through the list and print each value.
an other fibonacciList is created in the main function, so the display (if it was working) would show the content of this local list and not the global one.

Random 2d array isn't being printed

public class Alfabhto {
int[][] pinakas = new int[3][6];
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
System.out.println(pinakas[i][j]);
}
public int[][] Numbers() {
Random rand = new Random();
for (int i=0;i<3;i++)
{
for (int j=0;j<6;j++)
{
pinakas[i][j] = rand.nextInt(38)-12;
}
}
return pinakas;
}
}
First of all, I am very new at java. The main function works properly and the user is asked to give an input. Some elements aren't used here (like the gramata array) so ignore them.
The problem is: the method numbers should fill the pinakas array with random numbers and then print them. It does nothing if it's in the method. Outside it brings up errors because it can't get "pinakas" array or i and j. Any ideas?
There is several issues with that code, see comments:
// Need to import Random
import java.util.Random;
public class Alfabhto {
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// This neesd to be final for Numbers to access it
final int[][] pinakas = new int[3][6];
// There's no reason for Numbers to be public, or to extend Alfabhto, or in
// fact to be a class at all. Recommend making it a static method within
// Alfabhto (in which case gramata and pinakas must also be static), or an
// instance method if appropriate (in which case pinaka does not need to be
// final anymore, though you might leave it that way if you never
// intend to replace the array with a different one.
// Also recommend making that method (static or instance) a private method.
public class Numbers extends Alfabhto {
public Numbers() {
// Create this once and reuse it
Random rand = new Random();
// Note using <, not <=, on the loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
pinakas[i][j] = rand.nextInt(38) - 12;
System.out.println(pinakas[i][j]);
}
}
}
}
// Since Numbers is an inner class, we need to be able to create instances of Alfabhto
private Alfabhto() {
}
// We need something in Alfabhto to run the Numbers constructor
private void run() {
// Run the code in the Numbers constructor
new Numbers();
}
public static void main(String[] args) {
/* None of this does anything, presumably you'll use it later...
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
*/
// Run our run method, which will run the code in the Numbers constructor
new Alfabhto().run();
}
}
In your main function, you never create an instance of Numbers so whatever your wrote in there is not being called. Once you create a new Numbers(), it should print something out.

Why do I get a syntax error in the for-loop definition in this Java program?

I'm working on the below code to create an ArrayList, shuffle it, and take the first three elements but, for some reason, on the line when I start the for loop I get a syntax error on token ";"
import java.util.ArrayList;
public class cardsShuffle {
ArrayList<String> cards = new ArrayList<>()
for (int i = 0; i < 52; i++){
cards.add(String.valueOf(i+1));
java.util.Collections.shuffle(cards);
}
public static void main(String args[]){
cardsShuffle s = new cardsShuffle();
System.out.println(s.cards.get(0));
System.out.println(s.cards.get(1));
System.out.println(s.cards.get(2));
}
You are missing the semicolon after the line "ArrayList cards = new ArrayList<>()".Just put a semicolon and your code will be error free :)
Try this
import java.util.ArrayList;
public class cardsShuffle {
public static void main(String args[]) {
ArrayList<String> cards = new ArrayList<>();
for(int i = 0; i<52;i++)
{
cards.add(String.valueOf(i + 1));
java.util.Collections.shuffle(cards);
}
cardsShuffle s = new cardsShuffle();
System.out.println(cards.get(0));
System.out.println(cards.get(1));
System.out.println(cards.get(2));
}
}
You cannot just put code into a class. It needs to be inside inside a method, constructor or initializer block or the RHS of a field initialisation (not possible for loops).
Furthermore you don't need to shuffle after adding each card. Since Collections.shuffle produces a random permutation, using it once after the loop is sufficient.
public class cardsShuffle {
// field declaration
ArrayList<String> cards;
// constructor
public cardsShuffle() {
cards = new ArrayList<>();
for (int i = 0; i < 52; i++){
cards.add(String.valueOf(i+1));
}
java.util.Collections.shuffle(cards);
}
public static void main(String args[]) {
cardsShuffle s = new cardsShuffle();
System.out.println(s.cards.get(0));
System.out.println(s.cards.get(1));
System.out.println(s.cards.get(2));
}
}
You have written the for loop outside function. All things other than deceleration should be written inside function or blocks.
import java.util.ArrayList;
public class CardsShuffle
{
public static ArrayList<String> cards = new ArrayList<>();
public static void main(String args[])
{
System.out.println(cards.get(0));
System.out.println(cards.get(1));
System.out.println(cards.get(2));
for (int i = 0; i < 52; i++)
{
cards.add(String.valueOf(i+1));
java.util.Collections.shuffle(cards);
}
}
}
The code should be something like this...always things to execute inside the function.

Random method for a quiz

Each method contain a question with multiple choice. When i call the method in the main, i need to shuffle it and make sure there are no repetition.
public static void main(String[] args) {
question_1();
question_2();
question_3();
question_4();
//continue to question 15
question_15();
}
thing that i tried.
int question_A = question_1();
int question_B = question_2();
int question_C = question_3();
int question_D = question_4();
//to question 15
int question_O = question_15();
//then i created an array
int [] question = new int[14];
question[0] = question_A;
question[1] = question_B;
question[2] = question_C;
question[3] = question_D;
//to last array
question[14] = question_O;
//to random it here is the code
Random r = new Random();
for (int counter = 0; counter <10; ++counter){
int swap_Index = r.next Int(15-counter)+counter; //there is an space between next Int, that because i was getting not properly formatted in the edit box
int temp = question[counter];
question[counter] = question[swap_Index];
question[swap__Index] = temp;
int[] question_To_Ask = new int[10];
for (int count = 0; count<10; ++count){
question_To_Ask[count] = question[count];
}
The reason the random does not work is because it starts executing the program at
int question_A = question_1();
for the random, i also tried any way such as Math.random. None of these worked and yeah, please do not use advance technique to solve this problem as i am a beginner.
The easy way to do this is using a list:
List<Question> questions = new ArrayList<Question>();
questions.add(question_1);
questions.add(question_2);
questions.add(question_3);
.....
Collections.shuffle(questions);
See, I dunno what you are doing with all these methods, but let us consider another approach put every question in a database, use a Collection like say hashmap in ur java code access ur database and based on the id of the question u can call whichever question u want to call and for the shuffling part there is a predefined function called shuffle in java, u can use it to shuffle ur question collection. Just a suggestion, try it, i think it is a better approach.
You could do something like this
public static void main(String[] args) {
// declare the variables first
int q1 = 1;
int q2 = 2;
...
int q15 = 15;
int[] questions = new int[] { q1, q2, q3, q4, ... q15 };
System.out.println("Before Shuffle");
for (int i : questions) {
System.out.println(i);
}
shuffle(questions); // here we do the shuffle
System.out.println("After Shuffle");
for (int i : questions) {
System.out.println(i);
}
}
public static void shuffle(int[] questions) {
Random random = new Random();
for (int i = 0; i < questions.length; i++) {
int newIndex = random.nextInt(questions.length - 1);
swap(questions, i, newIndex);
}
}
private static void swap(int[] questions, int oldIndex, int newIndex) {
int temp = questions[oldIndex];
questions[oldIndex] = questions[newIndex];
questions[newIndex] = temp;
}

I need some help understanding instances/references

Just want to know if what I'm trying to teach myself is right.
I'll end up with something like this in one of my programs:
public class Test {
int array[];
public static void main(String[] args){
Test test = new Test();
test.array = new int[10];
test.fillArray();
for(int i=0;i<test.array.length;i++)
System.out.println(test.array[i]);
}
public void fillArray(){
Test test = new Test();
for(int i=0;i<test.array.length;i++)
test.array[i]=i;
}
}
But I get a null pointer exceptions. I seem to run into these types of issues a decent amount.. Would proper planning of my programs help with this?
The null Pointer was because when I say new it creates a separate object that only exists inside that method correct?
Are there any other ways to fix this other than making the array static or giving it a parameter (or is it argument..?) like I did below?
public class Test {
int array[];
public static void main(String[] args){
Test test = new Test();
test.array = new int[10];
test.fillArray(test.array);
for(int i=0;i<test.array.length;i++)
System.out.println(test.array[i]);
}
public void fillArray(int a[]){
for(int i=0;i<a.length;i++)
a[i]=i;
}
}
Your first fillArray has a shadowing problem in that you are creating a new test instance and initializing it - instead initialize the field array within the current (or this) instance,
public void fillArray() {
// Test test = new Test();
for (int i = 0; i < this.array.length; i++) {
this.array[i] = i; // <-- this.array or just array[i]
}
}

Categories