Outputting values in 2d array not working - java

I've tried several times but to no avail it's only outputting the first row. It's a 2D array, and it's supposed to output 4 rows. It's not showing any errors. I think the logical error may be from the for loops which contain the output statements.
package aitiDay5;
public class WorldCup {
public static void main(String[] args){
int i=0,j=0;
String [][] countries = new String [6][];
countries[0]=new String[4];
countries[1]=new String[4];
countries[2]=new String[4];
countries[3]=new String[4];
countries[4]=new String[4];
countries[5]=new String[4];
countries[6]=new String[4];
countries[0][0]="Countries ";
countries[0][1]="Rival ";
countries[0][2]="Grade ";
countries[0][3]="Points ";
countries[1][0]="Ghana";
countries[1][1]="Germany";
countries[1][2]="C";
countries[1][3]="3";
countries[2][0]="Croatia";
countries[2][1]="Greece";
countries[2][2]="B+";
countries[2][3]="A-";
countries[3][0]="USA";
countries[3][1]="Portugal";
countries[3][2]="B+";
countries[3][3]="4";
countries[4][0]="Spain";
countries[4][1]="Costa Rica";
countries[4][2]="F+";
countries[4][3]="-2";
countries[5][0]="Brazil";
countries[5][1]="Germany";
countries[5][2]="Z";
countries[5][3]="-32";
countries[6][0]="Argentina";
countries[6][1]="Holland";
countries[6][2]="A";
countries[6][3]="10";
for ( i=0;i<=countries.length;i++){
System.out.println("\n");
for(j=0;j<countries.length;j++){
System.out.println(countries[i][j]+ " ");
}
}
}
}

Your first for loop statement should just use the < operator, not the <= operator.
Your second loop should index into the row to check the length.
for (i = 0; i < countries.length; i++){
System.out.println("\n");
for(j = 0; j < countries[i].length; j++){
System.out.println(countries[i][j] + " ");
}
}
Also, since it appears you want 7 rows, you need to change
String [][] countries = new String [6][];
to
String [][] countries = new String [7][];
Side Note: you don't have to have i and j outside of the for loops. You can do this:
for(int i = 0; ......){ ... }

YOu need to change this line
for(j=0;j<countries.length;j++){
System.out.println(countries[i][j]+ " ");
To this:
for(j=0;j<countries[i].length;j++){
System.out.println(countries[i][j]+ " ");
Otherwise it will just loop on the single array twice

The problem is simple and you are correct, there is a logical error in your nested for loop.
You are running it against the length of the entire array it should be changed to:
for(j=0;j<countries[i].length;j++){
System.out.println(countries[i][j]+ " ");
}

Your inner for loop statement should be for(j = 0; j < countries[i].length; j++), and your outer for loop should be for(i = 0; i < countries.length; i++).
As it stands you're not fully looping through the second dimension. I'm actually very surprised that you're not seeing an error, because based on your arrays you should have a ton of illegal access exceptions. Java gets really upset when you try to access past the end of an array (example: your inner arrays only contain 4 elements, but your inner for loop iterates until j=5, meaning you're accessing the 5th element in a 4-element array)

Related

Check number of character from command line

I am trying to solve this question: Write a program that passes a string to the command line and displays the number of uppercase letters in the string.
The test is ProgrammingIsFun, so the count would be three.
Here is what I have so far
public static void main(String[] args) {
int count = 0;
for(int i = 0; i < args.length;i++) {
for(int j = 0; j >= i; j++)
if(Character.isUpperCase(args[i].charAt(j)))
count++;
}
System.out.print("The number of upper cases are: " + count);
}
when this runs it does count the correct number of uppercases but it runtimes when it reaches the end of the characters(16). I can't figure out how to stop the loop right after the last character. I know the count is correct because I can see it in the debug. I can see something called arg0 in the variables. That has the correct number of characters but I can't use it.
I am still learning and I can't use objects or anything like that for now.
Any help would be appreciated. or if you could point me somewhere I could read. I tried the docs but it was a lot and I got overwhelmed fairly quickly.
You have an error in the inner loop:
for(int j = 0; j >= i; j++)
Note that the outer loop is run for each of the command line argument and the inner loop is run for each character of an argument given by i.
So change it to
for(int j = 0; j < args[i].length(); j++)
for(int j = 0; j < args[i].length(); j++)?
This will sum all uppercases for all strings passed as arguments.
Your code could be simpler if you only expect one string.
To make your code easier to read (and write) you should use foreach loops, one for each string in the args array, and one for each character in the array that we get by doing foo.toCharArray().
The syntax of a foreach loop is as follows:
for (type var : iterable) {
// Code here
}
Where iterable is something with the Iterable interface (usually an array or ArrayList).
We can switch out these in your code and make it a lot easier to read:
String[] args = {"ProgrammingIsFun!", "When It Works..."};
int count = 0;
for (String e : args) {
for (char f : e.toCharArray()) {
if (Character.isUpperCase(f)) {
count++;
}
}
}
System.out.print("The number of upper cases are: " + count);

How to turn an array of Strings into an Array of Ints?

I'm new to Java programming, but after looking around on this site, I'm fairly certain this should work.
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
What I want this method to do is take an input array: ["1","2","3"] with each item being a string
and return [1,2,3] where each item is an int.
I'm calling the method with this code
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
In this case, toBeSorted is both being declared here and initialized at the same time.
Whenever I try to run this I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at sorter.Sorter.ArrayStringToArrayInt(Sorter.java:31)
at sorter.Sorter.main(Sorter.java:22)
Java Result: 1
Line 31 is the body of my For loop, the part that does the parsing, and line 22 is the place where the method is called.
The reason I need this is because I'm trying to take an input from the user, with the Scanner class and want them to be able to enter many numbers at the same time. I then use a delimiter pattern to turn the input into an array. While that seems fine, I could only figure out how to make the input be an array of strings, not ints, which is my problem.
So I guess what I'm asking is
1) why does my code not work?
and
2) is there an easier way to take an input from the user and turn it into an array of ints than this?
For those who would like to see my entire code, here it is
The bit in the middle with the test variable and the adding of two numbers is just a way for me to test my code and see if it worked. It should show the result of adding the first two numbers in the list that you entered
package sorter;
import java.util.Scanner;
import java.util.Arrays;
public class Sorter {
public static void main(String[] args) {
Scanner userInput = new Scanner( System.in );
System.out.println("Enter a list to be sorted, seperate numbers by commas:");
String input = userInput.nextLine(); //Gets aan input as a String
String delims = "[,]+"; //Use Comma as Delimiter
String[] inputStringArray = input.split(delims); //Parse String and creates
//an array
System.out.println(Arrays.toString(inputStringArray)); //Outputs a string of
//the given array
int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
int test = toBeSorted[0] + toBeSorted[1];
System.out.println(test);
}
public static int[] ArrayStringToArrayInt(String[] arrayString) {
int[] arrayInt = new int[arrayString.length]; //Array of Ints for output
for (int i = 0; i <= arrayString.length; i++ ) { //Run through the
arrayInt[i] = Integer.parseInt(arrayString[i]); //array, Parsing each
} //item into an int
return arrayInt;
}
}
You got the range of the loop wrong :
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The valid indices of the array are between 0 and arrayString.length - 1.
As a bonus, here's a nicer way to achieve the same with Java 8:
public static int[] ArrayStringToArrayInt(String[] arrayString)
{
return Stream.of(arrayString).mapToInt(Integer::parseInt).toArray();
}
Off-by-one error here:
for (int i = 0; i <= arrayString.length; i++ ) {
^
It should be:
for (int i = 0; i < arrayString.length; i++ ) {
This is wrong
for (int i = 0; i <= arrayString.length; i++ )
should be
for (int i = 0; i < arrayString.length; i++ )
The indexes of the array are between the 0 and length -1
Variable i should go from 0 to N-1, N being the length of the array. Java arrays, like C ones are zero-based, which means that you should iterate them from 0 to N-1. So your for should look like this:
for (int i = 0; i < arrayString.length; i++)
You could use a stream:
Arrays.stream(arrayString).mapToInt(Integer::parseInt).toArray()
Simply change this statement
for (int i = 0; i <= arrayString.length; i++ )
To
for (int i = 0; i < arrayString.length; i++ )
It will work fine. ArrayIndexOutOfBoundsException means you're trying to access an index in the array that does not exist.
For example,
int [] a= new int [5];
Then the indices available to me are
a [0], a [1], a [2], a [3], and a [4]
I cannot access
a [5]
And if i try i would get ArrayIndexOutOfBoundsException.
That means array indices start at 0 and go upto array length-1.
Hope this helps.

Loop with incremental value based on user input

I have a task about incremental values in a loop based on user input.
The task is that the following lines are generated in the console
*
**
***
****
*****
And the amount of lines are decided by user input. I.e. if the user types in 2 it gives the following output:
*
**
My current code is:
import static javax.swing.JOptionPane.*;
public class loop1 {
public static void main(String[] args){
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
while (current_line != target_line){
String sign = "*";
System.out.println(sign);
current_line ++;
}
}
}
But I can't seem to get the number of asterisks (*) to increase for every time it runs. How can I accomplish this?
You need a nested loop. Each iteration of the outer loop (which is the loop you already have) would print a single row, and each iteration of the inner loop would print a single asterisk for the current row.
You actually need two loops here, but you only have one. You have a while loop to print out the asterisks, but you also need a loop to increment the number of asterisks printed out each time.
Some pseudocode might look like:
For (int i = 1 to whatever value the user entered):
For (int j = 1 to i):
Print an asterisk
Actual code would look like:
int numLines = Integer.parseInt(showInputDialog("type here "));
for(int numAsterisks = 0; numAsterisks < numLines; numAsterisks++) {
for(int i = 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println(); // Start a new line
}
You can make it simpler by using nested for loops. Modify your loop to:
for (int i=0;i<target_line;i++) {
for (int j=0;j<=i;j++) {
System.out.print("*");
}
System.out.println();
}
You print everytime one '*'-sign.
You don't necessarily need two loops. You can place the sign outside of the loop and you can add an asterisk every iteration with string.concat("*"). Concatenating actually means combining two strings into one, so you actually combine the sign from the previous iteration with a new sign.
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
String sign = "*";
while (current_line != target_line){
sign.concat("*");
System.out.println(sign);
current_line ++;
}

Array error with string

I have an issue with string array where's the program takes the use names the put it in the screen. I did some coding and creating 2D games and android app but the fact I never used array for saving scores or something and now I'm stuck and need to learn it and code below think of it as we are putting degrees for collage students put the error that the array is making an error and I can't figure it out why the full code below:
public static void main(String[] args) {
// TODO Auto-generated method stub
Chatlength = new String[10];
for(i =0; i <= Chatlength.length ; i++){
Scanner s = new Scanner(System.in);
String ss = s.nextLine();
Chatlength[i] = ss;
}
while(true){
if(i > Chatlength.length){
int ints = 0;
while(ints <10){
System.out.println("Name "+ints+": "+Chatlength[ints]);
ints++;
}
}
}
It gives me and error with Chatlength[i] = ss;.
I'm guessing you're getting an ArrayIndexOutOfBoundsException due to your loop bounds:
for(i =0; i <= Chatlength.length ; i++){
That should be:
for (int i = 0; i < Chatlength.length; i++) {
... using a local variable declaration instead of the static variable which I assume you've declared in code that you haven't shown us.
An array of length 10 has valid indexes of 0 to 9 inclusive. It's very rare that you actually want <= for a loop index variable when you're trying to iterate over a collection. (All the standard collections in Java are 0-based, so you pretty much always want to have an exclusive upper bound.)
Additionally, I strongly suggest that you start following Java naming conventions.
The condition is culprit. You are going one plus the size of array.
i <= Chatlength.length
Change it to
i < Chatlength.length
Check your for - loop:
for(i =0; i <= Chatlength.length ; i++)
should be
for(i =0; i < Chatlength.length ; i++)
you didn't declare the array first:
Chatlength = new String[10]; //Wrong code;
change it to :
String[] Chatlength = new String[10];
then java is zero based and you should use this:
for(i =0; i < Chatlength.length ; i++)
There is no such index i=10 for the array you created, as per your condition in loop, it allows i=10 (i<= Chatlength.length) which is not a valid array location hence you got the exception

Java loop output keep on repeating

String[] month = {"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
int[] monthArray = new int[12];
String[][] itemArray = new String[12][10];
Variables
monthArray[i] = input.nextInt();
itemArray[monthArray[i]-1][e] = input.next();
Store a maximum of 5 String values on user input's month.
for(int i=0;i<e;e++){
System.out.println(itemArray[monthArray[i]-1][i]);
}
Having a problem displaying the String values (it just keep repeating the first String value) under user input's month.
You are increasing e instead of i in the last loop. e is the limit and not the variable you use for the iteration and thus the loop will not terminate until you overflow int.
for(int i = 0; i < e; i++ /* Note the usage of i here*/) {
use i++ instead of e++
here e stands for the limit
and i stands for the variable.
Since you have a 2D array, maybe you want something more like this, to print out the values, once, the array has been populated.
String[][] itemArray = new String[12][10];
for(int i = 0; i < itemAreray.length; i++){
for (int j = 0; j < itemArray[i].legnth; j++){
System.out.println(itemArray[i][j]);
}
}
Unless you're having difficulty populating the array. Then that's a different problem

Categories