Input and storing Strings in two-dimensional arrays - java

My teacher explained two dimensional arrays in literally two paragraphs. He didn't give me any information on how to create them besides that and now I have to do an assignment.
I've read up a lot about it and I somewhat understand how a 2D array is like an array of arrays, but I'm still completely and utterly confused about how to apply it.
The assignment itself is very simple. It asks me to create a program that will ask a user for ten Criminal Records, (name, crime, year). This program will store the records in a two-dimensional array and then sort them using the selection sort.
I know this is probably wrong, but here is what I have so far based on what I've read:
public static void main(String[] args)throws IOException {
//create array
String[][] Criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 1; row < Criminals.length; row++){
for (int col = 1; col < Criminals[row].length; col++){
System.out.print("Enter a criminal name: ");
Criminals[row][col] = br.readLine();
}
}
}
So far, I'm just trying to get the input and store it.
(Please try to be patient and thorough with me! Coding isn't my strongest point, but I'm trying to learn.) Any help would be amazing! Thanks in advance. :)

It looks fine for the most part. You should index arrays starting from 0, not 1. Your current code works but I'm guessing you don't want the same prompt for all entries. Thus it may be a good idea to use a single loop instead:
for (int row = 0; row < Criminals.length; row++) {
System.out.print("Enter a criminal name: ");
Criminals[row][0] = br.readLine();
System.out.print("Enter a crime: ");
Criminals[row][1] = br.readLine();
System.out.print("Enter a year: ");
Criminals[row][2] = br.readLine();
}

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//create array
String[][] criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 0; row < criminals.length; row++){
System.out.print("Enter a criminal name: ");
while(in.hasNext()){
criminals[row][0] = in.nextLine();
System.out.print("Enter a crime: ");
criminals[row][1] = in.nextLine();
System.out.print("Enter a year: ");
criminals[row][2] = in.nextLine();
}
}
}
}
This will print the commands you need from user and will store it in criminals. You may sort in the end. Since you didn't gave any information how you want it sorted, I will leave it for you to do it.
PS: I changed the 2d array name from Criminals to criminals, it's a java's good practice to not use capital words for attributes and variables (use it only for class names)

Related

Printing Arrays back to user (java)

I'm quite new to java programming so excuse the basic misunderstandings and interpretations of the fundamentals.
This program is supposed to ask the user for the size of an array, then ask the user for input n amount of times and then prints the array back to the user. So far, the first 2 parts work. The program asks for the size of the array and then prints "Enter element n: " based on how many times the user specified in part 1. However, i can't seem to figure out how to print back the string input back out (In my first for loop) the second for loop i tried does not work and just ends the program straight after the first for loop finishes executing. If anyone could help me it would be much appreciated and contribute to my learning of the basics of java. Cheers.
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter array size: ");
int arraySize = scanner.nextInt();
int[] array = new int[arraySize];
for (int i = 0; i<array.length; i++){
System.out.print("Enter element " + (i + 1) + ": ");
String element = scanner.next();
}
System.out.print(array[0]);
for (int i = 1; i < array.length; i++){
System.out.print(array[i]);
}
System.out.println("}");
}
You're not storing any input value into the array.
replace this line:
String element = scanner.next();
with the following one:
array[i] = scanner.nextInt();

Java: I made a program that accepts input for an integer array & displays values in a table. Trying to recreate this using a string array. Pls. help,

Java is my first programming language, and I'm still unfamiliar with how arrays work. However, I was able to make this program, which accepts user-input for an integer array; it then outputs indexes and values, to show how arrays store numbers. I would like to recreate this program using a string array, to make a table containing a list of friends.
The .length property also confuses me...
Could someone explain the .length property and help me make the string array program work?
Thank you very much.
Here is the working code for the integer array table program
import java.util.*;
public class AttemptArrayTable
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Let me show you how arrays are stored ");
System.out.println("How many numbers do you want your array to
store? ");
int arrayInput [] = new int[scan.nextInt()];
System.out.println("Enter numbers ");
for (int count = 0; count<arrayInput.length; count++)
arrayInput[count] = scan.nextInt();
System.out.println("");
System.out.println("Index\t\tValue");
for (int count2=0; count2<arrayInput.length; count2++)
System.out.println(" [" + count2 + "]"+"\t\t " + arrayInput[count2]);
}
}
Here is the code for the string array program I'm working on
import java.util.*;
public class ArrayTableofFriends
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many female friends do you have? ");
String arrayOfFriendsFem [] = new String [scan.nextInt()];
System.out.println("List the name of your female friends");
for(int countF = 0; countF<arrayOfFriendsFem.length; countF++)
arrayOfFriendsFem[countF]= scan.nextLine();
System.out.println("How many male friends do you have? ");
String arrayOfFriendsMale [] = new String [scan.nextInt()];
System.out.println("List the name of your male friends");
for(int countM = 0; countM<=arrayOfFriendsFem.length; countM++)
arrayOfFriendsMale[countM]= scan.nextLine();
System.out.println("How many alien friends do you have? ");
String arrayOfFriendsAliens [] = new String [scan.nextInt()];
System.out.println("List the name of your alien friends");
for(int countA = 0; countA<=arrayOfFriendsFem.length; countA++)
arrayOfFriendsAliens[countA]= scan.nextLine();
{
System.out.println("Female\t\t\t" + "Male\t\t\t" + "Aliens");
for(int countF2 = 0; countF2<arrayOfFriendsFem.length; countF2++)
System.out.println(arrayOfFriendsFem[countF2]);
for(int countM2 = 0; countM2<=arrayOfFriendsMale.length; countM2++)
System.out.println("\t\t\t" + arrayOfFriendsMale[countM2]);
for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
System.out.println("\t\t\t\t\t\t" +arrayOfFriendsAliens[countA2]);
}
}
.length property stores number of elements in the array. But elements are starting from 0. So, when .length = 1, then there is only one element in the array, with index 0.
It seems in your String arrays program in the for loop the <= should be changed to <
Like this:
for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)

An array that takes the size depending on what I enter [duplicate]

This question already has answers here:
Enter array without knowing its size
(6 answers)
Closed 5 years ago.
import java.util.Scanner;
public class Singleton{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
int number = input.nextInt();
String names[] = new String[number];
for(int counter = 0; counter < 100; counter++){
System.out.print("Enter name: ");
names[counter] = input.nextLine();
names[counter] = names[counter].toLowerCase();
}
int grades[] = new int[names.length];
int count = 0;
for(String x: names){
System.out.print(x + "'s grade: ");
grades[count] = input.nextInt();
count++;
}
count = 0;
for(String x: names){
System.out.println(x + "'s grade is " + grades[count] + ".");
count++;
}
}
}
can you help me to get something so I can put any number of values in the array without asking how many students there are?
If you want an array that you can add a variable number of elements to you could use an ArrayList. i.e.
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<String>();
for(int counter = 0; counter < 100; counter++){
System.out.print("Enter name: ");
names.add(input.nextLine());
}
You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
Java has fixed length array and it is not possible to change size of array dynamically. To do what you need there is java.util.ArrayList class.
(look at Reginol_Blindhop's answer. Regardless is it ArrayList or LinkedList code is the same).
But if you need array you can create new array with +1 size for every input, copy previous values there and put new into last element. To do that there is System.arraycopy method.
code may look like:
String[] names = new String[1];
for(int counter = 0; counter < 100; counter++){
System.out.print("Enter name: ");
String nextName = input.nextLine();
String[] tempNames = new String[names.length + 1];
System.arraycopy(names, 0, tempNames, 0, names.length);
tempNames[names.length] = nextName;
names = tempNames;
}
PS. Of course for any solution it is better to use while loop and check if user finishes input by putting something special like "exit", "end", "bye", ":q" or whatever you'd like.

Asking the user to enter amount of items to an array

I'm really new to Java and I am having some difficulty with the basics of arrays. Some help would be greatly appreciated :).
I created a program that asks the user to enter values into an array. The program then tells the user how many items are in the array, the even numbers that are in the array, the odd numbers in the array and the average of all the numbers in the array.
My problem is this: At present my program has a set number of values in the array which is 5 items. I want to change this so that the user can determine the amount of items they want in the array, and ask the user to continually add values to the array until they enter 'Q' to quit entering values so that the program can continue.
I do not want to modify my code, just the part where the user determines the amount of items in the array.
This is my code:
//main class
public class Even_number_array {
public static void main(String[] args) {
array_class obj=new array_class();
obj.get_numbers();
obj.set_arraylist();
obj.set_numbers();
obj.get_average_of_array();
}
}
//another class
import java.util.Scanner;
public class array_class {
private int[] arr=new int[5]; //here is where I would like to modify my code so
//that the user can determine amount of items in array
Scanner keyboard=new Scanner(System.in);
public int[] get_numbers() //asks user to add items to array
{
System.out.println("Please enter numbers for array :");
for (int i=0; i<this.arr.length; i++)
{
this.arr[i] = keyboard.nextInt();
}
System.out.println("There are "+((arr.length))+ " numbers in array");
return this.arr;
}
public void set_numbers() //Tells user what even & odd numbers are in array
{
System.out.println();
System.out.println("These even numbers were found in the array:");
for (int i=0; i<arr.length;i++)
{
if (arr[i]%2==0)
{
System.out.print(arr[i]+" ");
System.out.println();
}
}
System.out.println("These odd numbers were found in the array:");
for (int i=0; i<arr.length;i++)
{
if ((arr[i]%2)!=0)
{
System.out.print(arr[i]+" ");
}
}
}
public void set_arraylist() //Dispalys all items in array
{
System.out.println("These are the numbers currently in your array: ");
for (int i=0; i<arr.length; i++ )
{
System.out.print(this.arr[i]+ " ");
}
}
public double get_average_of_array() //Gets average of all items in array
{
double sum=0;
double average=0;
System.out.println();
System.out.println("the average is: ");
for (int i=0; i<this.arr.length; i++)
{
sum=sum+arr[i];
average =sum/arr.length;
}
System.out.println(average);
return average;
}
}
Any help would be great!
Try:
public int[] get_numbers() {
System.out.println("Please enter numbers for array :");
int size = keyboard.nextInt();
int[] values = new int[size]; // create a new array with the given size
for (int i = 0; i < size; i++) {
values[i] = keyboard.nextInt();
}
System.out.println("There are "+((values.length))+ " numbers in array");
this.arr = values;
return this.arr;
}
Sorry i don't really get what you are asking but maybe you mean this
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int[] array = new int[scanner.nextInt()];
System.out.println(array.length);
Sorry i'm pretty bad in java only been learning it for 2 months now
ArrayList is the object you want. It has functions that allow you to append values at the end. It's a dynamic array in the sense that you can mutate it at will.
Using an ArrayList instead of arrays would be the easiest way to accomplish exactly what you are trying to do.
Another option is to ask how many numbers the person plans on entering from the start.
If, for some weird reason, you are only trying to use arrays without asking the user how many numbers they want to enter... a third option would be to create a new array (being one size larger than the previous array) each time the user enters another number.
Some guidance for the last piece...
public int[] get_numbers() //asks user to add items to array
{
System.out.println("Please enter numbers for array :");
//Instead of this for loop, you will want a while loop. Similar to "while (userHasntEnteredQ)"
for (int i=0; i<this.arr.length; i++)
{
//You will want to create a new array here.
// int[] newArray = new int[this.arr.length + 1];
// Then copy the values of this.arr to newArray
// Then place the keyboard.nextInt() into the last spot of newArray
// Then set this.arr to newArray
}
System.out.println("There are "+((arr.length))+ " numbers in array");
return this.arr;
}
If you want the user to determine how many items are in the array, add this in to your code:
System.out.println("Enter the amount of items in the array:");
while (keyboard.hasNextInt()) {
int i = keyboard.nextInt();
}
private int[] arr = new int[i];
However, you won't be able to add more items to the array than the user defined without getting an ArrayIndexOutOfBoundsException, so there is a better way to do this that uses something called an ArrayList. With an ArrayList, you don't have to worry about setting the size of the array before using it; it just expands automatically when new items are added unless you explicitly set a size for it. An ArrayList can be of any object, but to make it only for integers, declare it like this:
ArrayList<Integer> arr = new ArrayList<>();
To add items to the ArrayList:
arr.add(item);
To read a value by its index:
arr.get(index);
To get the index of an item:
int index = arr.indexOf(item);
There is much more that you can do with an ArrayList. Read about it here.

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

Categories