The way I have my code set up is I declare my array in one method then I want to print it out in a table like fashion in another. But I want to do this while only using the main() function.
I have taken most of the irrelevant code out so here is my code:
public static void main(String[] array) {
test2(array);
}
public static void test() {
String[] array = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
When I try and run it, it comes up with the java.lang.ArrayOutOfBound on the line "System.out.print(array[count] + "\t");"
Does anyone know why this is and/or how to fix it?
You have several errors:
You create array as a local variable in test().
You use the arguments of the application as parameters.
You don't even call test().
The consequences are that you call your application probably with no parameters and end up having the test2() method trying to access the first element of an empty array, causing your exception.
This is what you should do, but keep reading after the code, I'm not done:
public static void main(String[] args) { // This array is defined, but don't use it.
test2(test());
}
public static String[] test() {
return new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
This code has still issues. You indeed assume that you have 16 elements in your array. Yet you're not sure. Oh yes, you're sure because you've added them, but you shouldn't assume that it'll always be the case.
Therefore it's nice to check for the actual number of the elements anyways.
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (count < array.length) {
System.out.print(array[count] + "\t");
count++;
}
}
System.out.println();
System.out.println();
System.out.println();
}
}
Well, it doesn't work because when your "main" calls "test2(array)" it passes nothing, since main doesn't have an "array" defined in it.
The array that you want exists only inside the "test" method.
So, one simple solution would be to change your code to:
public static void main(String[] array) {
test2(test());
}
public static String[] test() {
String[] array = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"};
return array;
}
public static void test2( String[] array ) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[count] + "\t");
count++;
}
System.out.println();
System.out.println();
System.out.println();
}
}
...so that the method test() returns the array when it's called in main.
But, still, the code doesn't make lots of sense, especially in Object Oriented programming.
Related
Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
I don't understand what is the correct way to call a function which accepts a multidimensional array as a parameter(a parameter of type int[][] for example).
The function's form is
public static int llamarArreglo(int[][] array){ ... }
I tried to call the function from within the main class by creating an array, and then trying to print a specific slot in the array, and it should print a 1 (because function 'llamarArreglo' fills an array with 1s the diagonal, and the rest of the slots is 0):
int[][] arr = new int[3][3];
System.out.print(llamarArreglo(arr[2][1]));
This is not compiling correctly, code inside the function works if I evaluate it in main class, without using a function/method. I beleive that I am not understanding how to call the function from the main class.
If you prefer to look at the complete, minimal code, there it is:
public class ArreglosMultidimensionales {
public static int llamarArreglo(int[][] array) {
int i;
int j;
for(i=0; i<array.length; i++){
for(j=0; j<array[i].length; j++){
if (i == j) {
array[i][j]=1;
}else {
array[i][j] = 0;
}
}
}
}
public static void main(String[] args) {
int[][] arr = new int[3][3];
System.out.print(llamarArreglo(arr[2][1]));
}
}
Thanks, if there is such help.
Try to use this: llamarArreglo(arr) like below.
public class ArreglosMultidimensionales {
public static void llamarArreglo(int[][] array) {
int i;
int j;
for (i = 0; i < array.length; i++) {
for (j = 0; j < array[i].length; j++) {
if (i == j) {
array[i][j] = 1;
} else {
array[i][j] = 0;
}
}
}
}
public static void main(String[] args) {
int[][] arr = new int[3][3];
llamarArreglo(arr);
}
}
I am new to coding and I have to code a NxN star grid as assignment. There is a tester program of the professor which gives input and tests the code.
The problem is that we have to write the code as a method and the test gets whatever I put to my return statement as the result instead of the correct output. How can I rearrange the code that the return statement will give me the result?
public class Assignment
{
public static void main(String[] args)
{
run(0);
}
public static int run(int i)
{
for (int row = 0; row < i; row++)
{
for (int col = 0; col < i; col++)
System.out.print("*");
System.out.print("\n");
}
//How can I change the return so that the tester gets the
//correct result?
return ?output?;
}
}
If I understood you well, you want to have result in some object to return it. There are many possibilities, for example:
public static String run(int size) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
sb.append("*");
}
sb.append("\n");
}
System.out.println(sb.toString());
return sb.toString();
}
You need to change a return type to String.
How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}
currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms.
Here is the challenge:
I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number.
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
public void recursion(ArrayList<Integer> specs){
//number of nested loops will be equal to: specs.size();
//each item in specs, specifies the For loop max count e.g:
//First outside loop will be: for(int i=0; i< specs.get(0); i++)
//Second loop inside will be: for(int i=0; i< specs.get(1); i++)
//...
}
The the results will be similar to outputs of this manual, nested loop:
int[] i;
i = new int[7];
for( i[6]=0; i[6]<5; i[6]++){
for( i[5]=0; i[5]<7; i[5]++){
for(i[4] =0; i[4]<9; i[4]++){
for(i[3] =0; i[3]<2; i[3]++){
for(i[2] =0; i[2]<8; i[2]++){
for(i[1] =0; i[1]<9; i[1]++){
//...
System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]);
}
}
}
}
}
}
I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.
// ...
recursion (specs, specs.size () - 1);
// ...
public void recursion(ArrayList<Integer> specs, int startWith){
for (int i = 0; i < specs.get(startWith); i++) {
// ...
if (startWith - 1 >= 0)
recursion (specs, startWith - 1);
}
}
Your function also need to now the index of the specs array to use for iteration, and also the previous numbers that should be printed:
public void recursion(ArrayList<Integer> specs, int index, String output) {
if( index >= specs.size() ) {
System.out.println(output);
return;
}
for (int i = 0; i < specs.get(index); i++ )
recursion( specs, index+1, Integer.toString(i) + " " + output );
}
The you should call it like this:
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5);
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
recursion( specs, 0, "" );
Does this snippet give the output you want? (It is compileable and executeable)
import java.util.ArrayList;
import java.util.List;
public class SO {
static ArrayList<Integer> specs = new ArrayList<Integer>();
static int[] i;
public static void main(String[] args) throws Exception {
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
i = new int[specs.size()];
printMe(0, specs, i);
}
static void printMe(int depth, List<Integer> _specs, int[] i) {
if (_specs.isEmpty()) {
System.out.println(printI(i));
return;
} else {
for (int j = 0; j < _specs.get(0); j++) {
i[depth] = j + 1; // + 1 since you seems to want to go from 1 and not 0
printMe(depth + 1, _specs.subList(1, _specs.size()), i);
}
}
}
static String printI(int[] i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i.length; j++) {
sb.append(i[j]);
if (j < i.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}
You can try this :
public static void loops(ArrayList<Integer> specs, int idx, StringBuilder res){
if(idx==specs.size()-1){
for (int i = 0; i < specs.get(idx); i++) {
System.out.println(i+" "+res);
}
}
else{
for(int i=0;i<specs.get(idx);i++){
res.insert(0,i+" ");
loops(specs,idx+1,res);
res.delete(0, 2);
}
}
}
And call with :
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
loops(specs,0, new StringBuilder());