What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}
Related
The Return type is void
No input parameters
Print out the numbers calculated results separated by a space using current number add the next number from 0 to (a+b).
An example would be if the numbers for the for loop are 0,1,2,3,4,5,6 then it would add 0+1, 1+2, 2+3, 3+4, 4+5, 5+6 and print out those values just like 0,1,2,3,4,5,6.
I honestly have no clue how to do this so I'm not going to lie about it so can someone help me code it and explain or just help me with it.
public class ForFogMe
{
public int a, b;
public String str;
public void addUp(){
for(a = 0; a <= 6; a ++){
System.out.print(a);
}
String s = Integer.toString(a);
System.out.println();
System.out.print(s.substring(0,2) );
}
public static void main(String args[]){
ForFogMe me = new ForFogMe();
me.addUp();
}
}
If you only want to print sum of the numbers from 0 to 6 you would do it simply like this:
public void addUp() {
for(a = 0; a < 6; a++) {
System.out.print(a+(a+1) + ",");
}
System.out.print("\b"); // to delete last comma
}
In first iteration a is 0 a+1 is 1 so you print their sum like (a+(a+1) + ",") which outputs "1,". It repeats until it reaches 6. At the end we have 1,3,5,7,9,11, so I used System.out.print("\b"); to delete last char, so we get 1,3,5,7,9,11
I believe this should do the trick:
public static void addUp(){
final int[] array = {0,1,2,3,4,5,6};
int[] result = new int[array.length-1];
for(int i = 0; i < array.length-1; i++) {
result[i]=array[i]+array[i+1];
}
result[3]=array[array.length-1];
for(int i = 0; i < result.length; i++) {
System.out.print(result[i]+" ");
}
}
Test case (array):
0,1,2,3,4,5,6
Outputs:
1 3 5 6 9 11
Note: The array size does not matter.
I am a beginner in Java and would like to ask some help with a array problem I am having. I am trying to build a simple program that has two int type arrays with 5 integers in each array. I want to divide the length of integers in one array by the length of integers in the other array. My program seems to work to some extent, since it gives me the results of the divisions. However it also gives me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at ArrayDivide.main(ArrayDivide.java:11)
Can someone tell me once going wrong? Here is my code:
public class ArrayDivide {
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
for (int j =0;x <arr2.length;j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
}
}
Divide each number of outer array (arr1) with respective number in other array(arr2)
The code is shown below. You should also put check to verify that both arrays have same length.
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
int result = arr1[x] / arr2[x];
System.out.println(result);
}
}
Output is:
4
1
3
8
2
Divide each number of outer array(arr1) with each number in other array (arr2)
And if you want to divide each number of outer array with each number of inner array then use the below code. In your code condition is not right, it should be j <arr2.length and not x <arr2.length.
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int i=0; i<arr1.length; i++){
for (int j =0;j<arr2.length;j++){
int result = arr1[i] / arr2[j];
System.out.println(result);
}
}
}
Change second loop to
for (int j =0;j <arr2.length;j++){
ie j <arr2.length from x <arr2.length
Loop
for (initialization; condition ;updation)
Since you dint compare j in condition part loop moves on giving you exception at the 5th index
public class ArrayDivide {
public static void main(String[] args) {
int arr1[]={8,4,6,8,4};
int arr2[]={2,4,2,1,2};
for (int x =0;x <arr1.length;x++){
int result = arr1[x] / arr2[x];
System.out.println(result);
}
}
}
ArrayIndexOutOfBoundException exceptions occurs when you try to access an item who's index is greater than the array's size.
Here in the above code :
for (int x =0 ; x < arr1.length ; x++){
for (int j =0 ; 0 < arr2.length ; j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
You have x < arr2.lengh.
Suppose your arr1 length is 10 and arr2 length is 5, in this case when j ll be 6, it ll still be less than 10 and your code int result = arr1[x] / arr2[j]; ll try to access arr2[6] which ll produce an ArrayIndexOutOfBoundException.
To fix this, in the inner loop you need to check from 0 to arr2's length.
Answer :
for (int x =0;x <arr1.length;x++){
for (int j =0;x <arr2.length;j++){
int result = arr1[x] / arr2[j];
System.out.println(result);
}
}
I'm playing around with double arrays and am trying to set all the even elements of an array to 0 and all of the odd elements of the array to 1. Everything looks okay to me, but when I run it I get a bunch of errors. Not sure what's wrong; I've been looking at it for a while with no luck. Any advice on how to fix the errors it gives would be great, thanks!
Code:
public class SetOf0and1 {
public static void main(String[]args)
{
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
System.out.println("Before setting elements between 0 and 1: ");
displayArray(numbers1);
setEvenRowsTo0OddRowsTo1 (numbers1);
System.out.println("After setting the elements between 0 and 1");
displayArray(numbers1);
}
public static void setEvenRowsTo0OddRowsTo1(int [][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array[i].length;j++)
{
if(i%2 == 0)
array[i][j]=0;
else
array[i][j]=1;
}
}
}
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
}
}
Errors given:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at SetOf0and1.displayArray(SetOf0and1.java:38)
at SetOf0and1.main(SetOf0and1.java:10)
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
^^^^^^^^^
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
Your inner loop should stop at array[i].length.
In the method displayArray, the line:
for( int j=0; j<array.length;j++)
Should be:
for( int j=0; j<array[i].length;j++)
array.length does not return the length you thing it does! You have a 2 dimentional array. So if we say you have array[x][y] then array.length will be x and array[i].length (for 0 <= i < x) will be y. This could be different depending on the length of the array on that index. (so the formula does not exactly apply like that)
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
this statement initializes an array with three arrays of the legthes 3, 3 and 2!!!
(in the third block you have only two elements !!! - {1,3})
In your displayArray-method you use two times ...
array.length
... to distinct the size of the loop
that sets the number of loops to 3 ... But last block is only two elements long -> errror.
Use this instead for the second loop:
for( int j=0; j<array[i].length;j++)
If you want to check if a number is odd, you can do it this way:
int answer = thenumber % 2;
'thenumber' is the integer to check if it is even.
Then 'answer' would be 0 if the number was even.
And if you want to loop through the array and do it:
for (int i = 0; i < numbers1.length(); i++)
{
if (numbers1[i] % 2 == 0) {
//EVEN
numbers1[i] = 0;
}
else if (numbers1[i] % 2 == 1) {
//ODD
numbers1[i] = 1;
}
}
And, even more compact:
for (int i = 0; i < numbers1.length(); i++)
{
numbers1[i] %= 2;
}
Edit: I forgot that it was an array you had! I was thinking about ArrayList! Fixed.
So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three.
I can print out the number of times three divides x like so:
public int Threes(int x){
int i = 0;
for(int counter = 1; counter <= x; counter++){
if (counter % 3 ==0){
i ++;
}
}
return i;
but I'm not sure how to print out each multiple of 3!?
for(int counter = 1; counter <= x; counter++){
if (counter % 3 ==0){
System.out.println(counter);
}
}
An even quicker approach would be to increment by 3
public void Threes(int x) {
for (int counter = 3; counter <= x; counter = counter + 3) {
System.out.println(counter);
}
}
This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void since you're printing instead of returning anything.
(Your title says 1 to n, but your question says 0 to n, so if you actually need from 0 to n, then change the declaration of counter to int counter = 0;)
Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.
public class byThrees {
public static void main(String[] args) {
for (int t = 100; t >= 0; t--) {
System.out.println(t*3);
Best practice using the For-loop in Java.
public class MultiplesOfThree {
public static void main(String []args){
for (int m = 1; m<=12; m++){
System.out.println(m*3);
}
}
}
Given an array a and two other int variables, k and temp, write a loop that reverses the elements of the array.
for (k = 0; k < a.length-1; k++) {
temp = a[k];
a[k] = a[a.length-1-k];
a[a.length-1-k] = temp;
}
This is not working. Any idea why?
E.g., for a = [0, 1, 2, 3, 4, 5] you'll switch 0 and 5 twice: when i == 0 and when i == 5. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5).
Try to make your loop to go through half of array only: so each pair is switched once.
You need to stop your loop at a.length/2 (in the middle).
for(k=0;k<a.length/2;k++)
This should work for odd and even length arrays if this is integer division.
check this at my blog hope this going to help http://codeheaven.wordpress.com/
Here is the code from above link:
public class ArrayReversing {
public static void main(String a[]){
int arr[]={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int temp;
int as = arr.length;
int k = as – 1;
System.out.println(“Array Before Reversing”);
printArray(arr);//method used to print array on screen
ArrayReverse://using loops with title
for(int i = 0; i < arr.length/2 ; i++){
temp = arr[k];// swaping
arr[k] = arr[i];
arr[i] = temp;
k–;
}
System.out.println(“Array After Reversing”);
printArray(arr); // calling the method printArray to print the elements of array
}
static void printArray(int ar[]){
PrintArray:
for(int l:ar)
System.out.println(l);
}
}
Output:
Array Before Reversing
1
2
3
4
5
6
7
8
Array After Reversing
8
7
6
5
4
3
2
1
Use a Stack. A stack reverses the elements that are added to it. A stack can be described as First In, Last Out (FILO). "Push" adds the elements to the stack and "Pop" removes them.
public static int[] num1 = {1,2,3,4,5,6};
public static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
for(int i = 0; i < num1.length; i++){
stack.push(num1[i]);
}
for(int i = 0; i < num1.length; i++){
System.out.print(stack.pop());
}
}
Output:
654321
You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?
You might also want to look at the ArrayUtils.reverse method.
Here is an example using that method.
I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.
This will work
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}
Try this will simply work:
public class ReverseArray{
public static void main(String[] args){
int[] a ={1,2,3,4,5};
for(int i=a.length-1;i>=0;i--){
System.out.print(a[i]);
}
}
}