Printing number in an array backwards - java

I am new to java and I wondering how I could fix my program which has to take numbers from user input, then store them in an array, and then print those numbers forwards and then backwards. I have managed to get the program to print forward; however, when I try to print it backwards I get
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at arrays4Days.arrayS1.main(arrayS1.java:55)
import java.util.*;
public class arrayS1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many numbers will you enter? ");
int count = console.nextInt();
int myArray[]= new int [count];
for (int i =0; i < myArray.length ; i++) {
System.out.print("Type a number: ");
int number=console.nextInt();
myArray[i]=number;
}
System.out.println();
System.out.println("Your numbers in forward order:");
for (int i = 0 ; i < myArray.length ; i++) {
System.out.println(myArray[i]);
}
System.out.println();
System.out.println("Your numbers in backward order:");
for (int i = myArray.length ; i> 0 ; i--) {
System.out.println(myArray[i]);
}
}
}

Note that in your first loop, i starts at zero and goes up to - but not equals - the length of the array
for (int i = 0 ; i < myArray.length ; i++) {
so the second loop should also start at this position
for (int i = myArray.length - 1; i>= 0 ; i--) {
System.out.println(myArray[i]);
}
and should go down to zero

Related

How to break correctlly in the array?

I have a question about break the input, because my code is typing two times "-1" to stop the input, actually I want to type "-1" single time to stop the input and then to show the array output.
Below is my code:
import java.util.Scanner;
public class NewTMA {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt(sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line break, end by -1:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++) {
for (int j=0; j<column; j++) {
String line = sc.nextLine();
if ("-1".equals(line)) {
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Below is my output:
run:
enter row size
3
enter column size
2
Type float numbers two-dimensional array of similar type and size with line breaks. end by -1:
1.4
2.4
-1
-1
The result is:
1.4 2.4
0.0 0.0
0.0 0.0
BUILD SUCCESSFUL (total time: 13 seconds)
Actually I just want to type "-1" a single time to stop the input,but I don't know why the output is showing "-1" twice to stop it. Hope someone can help me find which part I am doing wrong. Thanks.
break breaks out of the inner-most loop, so the outer loop iterates again and hits the input read again.
To break out of the outer loop, use a label:
outerLoop: // label the outer for loop
for (int i=0; i<row; i++){
for (int j=0; j<column; j++) {
String line = sc.nextLine();
if ("-1".equals(line)) {
break outerLoop; // break from the outer for loop
}
...
}
You can use any java allowable name for the label (I just called it “outerLoop” for clarity)
Another approach would be putting a flag as an indication if the argument is met:
for (int i=0; i<row; i++){
/* this is the flag */
boolean isInputNegative = false;
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
isInputNegative = true;
break;
}
a[i][j]=Float.parseFloat(line);
}
/* here is the checking part */
if (isInputNegative) {
break;
}
}

Count Occurence isn't adding

I was having trouble with this program that asks me : Write a program that generates 10 integers between 0-9 and displays the the count for each number. I am having trouble on the count occurrence for each of the single digit numbers. It seems my program dosen't add the counter right. Here is my program:
I've tried to read other code to help fix it but nothing worked.
import java.util.*;
import java.util.Arrays;
public class CountsArray {
public static void main(String[] args) {
int[] list = new int[10];
int[] num = new int[10];
for(int i = 0; i< list.length;i++) {
list[i] = (int)(Math.random()*10+1);
}
for(int i = 0; i< list.length;i++) {
System.out.print(list[i] + " ");
}
System.out.println();
int temp = 0;
for(int i = 0; i <num.length;i++) {
temp = num[i];
list[temp]++;
}
for(int i = 0;i < list.length;i++) {
if(list[i]>0 && list[i]==1) {
System.out.printf("%d occurs %d time\n",i, list[i]);
}
else if(list[i] >= 2) {
System.out.printf("%d occurs %d times \n", i, num);
}
}
}}
If the random numbers is : 1 1 2 2 2 3 3
The output should be 1 occured 2 times, 2 occured 3 times, 3 occured 2 times.
Could anyone point me in the right direction?
You can do it this way , first since random integers are 0 to 9 so adding 1 to Math.random() will also produce ten which will be wrong as per the question
then increment places in num (that is if you encounter 3 in list then increment num[3] by one as count of 3 is now 1) as you traverse the list and then print num if num[i]>0 as there might be integers which have not occured at all.
`int[] list = new int[10];
int[] num = new int[10];
for(int i = 0; i< list.length;i++) {
list[i] = (int)(Math.random()*10);
}
for(int i = 0; i< list.length;i++) {
System.out.print(list[i] + " ");
}
System.out.println();
for (int i = 0; i < list.length; i++) {
++num[list[i]];
}
for (int i = 0; i < num.length; i++) {
if(num[i]>0){
System.out.printf("%d occurs %d times\n",i,num[i]);
}
}`
One way to do this would be to make sure that the numbers were in order (have a look at Arrays.sort), and then loop over the array - if the current number is the same as the last, add to a count, or else start a new count for the new number.

Bug Printing List of Arrays in Java After Sorting

Im working on a project that consist of creating an array based on a number input, and then assigning int values through inputs. It then runs through a bubble sort to sort the values in increasing order. I am having trouble on the printing for this of all things. I use Eclipse as my IDE and I can't really make much of what I'm doing wrong. Any help would be greatly appreciated
import java.util.Scanner;
public class Ex07_18 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt user to enter the numbers of integers to be entered
System.out.print("Enter the number of integers:");
final int NUM_OF_INTS = input.nextInt();
int[] numbers = new int[NUM_OF_INTS];
// Input the numbers into an array
for (int i = 0; i < NUM_OF_INTS; i++) {
System.out.print("Enter an integer: ");
numbers[i] = input.nextInt();
}// end for
// Bubble sort the array
bubbleSort(numbers);
// Print out the integers
printList(numbers);
input.close();
}// end main
public static void bubbleSort(int[] list) {
int listLength = list.length;
int temp;
boolean is_sorted;
for (int i= 0; i < listLength; i++) {
is_sorted = true;
for (int j = 1; j < listLength; j++) {
if (list[j - 1] > list[j]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
is_sorted = false;
} // end if
} // end for
if (is_sorted) break;
} // end for
}// end bubbleSort
public static void printList(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++ ) {
// Print the numbers
System.out.print(numbers[i] + " ");
}// end for
}// end printList
}// end Ex07_18
In for loop in printList method you iterate through number.length - 1 elements instead of number.length elements. Your printList method should look like this:
public static void printList(int[] numbers) {
for (int i = 0; i < numbers.length; ++i ) {
// Print the numbers
System.out.print(numbers[i] + " ");
}// end for
}// end printList
In your printList function, you are setting the comparison condition incorrectly,
public static void printList(int[] numbers) {
for (int i = 0; i < numbers.length - 1; i++ ) { //should be i <= numbers.length - 1
// Print the numbers
System.out.print(numbers[i] + " ");
}// end for
}// end printList

Printing a 2d array in Java like a table [duplicate]

This question already has answers here:
How to print Two-Dimensional Array like table
(16 answers)
Closed 9 years ago.
I'd like to print an inputed 2-dimensional array like a table
i.e if for some reason they put in all 1s...
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Just like so above but in the console on Java eclipse, no fancy buttons and GUI's but in the console, here is what I have....
import java.util.Scanner;
public class Client {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i=0; i < table.length; i++) {
for (int j=0; j < table.length; j++) {
System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println(table);
}
}
And this is what I get when I input everything and the console terminates:
Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1 Enter a number.
1
1
[[I#3fa1732d
Consider using java.util.Arrays.
There is a method in there called deepToString. This will work great here.
System.out.println(Arrays.deepToString(table));
Relevant here: Simplest way to print an array in Java
You need to print out the array separately from entering the number. So you can do something like this:
public class PrintArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] table = new int[4][4];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
// System.out.println("Enter a number.");
int x = input.nextInt();
table[i][j] = x;
}
//System.out.println();
}
// System.out.println(table);
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}
You'll have loop back through those arrays to print out the contents. an array's toString() just prints the reference value.
System.out.print(table) calls a method in array class that prints out the identifier of the vairable. you need to either create a for loop that will print out each element like System.out.print(table[i][j]) or use the Arrays class and say Arrays.toString(table);
Try copying this simple for loop to printing a 4x4 table:
Scanner input = new Scanner();
int numArray [] [] = new int [4] [4];
for ( int c = 0; c < 4; c++ ) {
for (int d = 0; d < 4; d++) {
System.out.print("Enter number : ");
nunArray [c][d] = input.nextInt();
}
}
for (int a = 1; a<5;a++) {
for (int b = 1; b <5;b++) {
System.out.print(numArray [a][b]+" ");
}
System.out.println();
}

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories