How would I determine the smallest value which has been entered? - java

My code asks the user to enter values of animal species and then displays it back to them. I just need to finally add a part which also tells the user the most endangered animal (the one will the lowest entered number). I've looked around on some places and triec using x< min or x=MAX_VALE etc. I just can't seem to make anything work. Is there a method which would be more appropriate for my program?
import java.util.Scanner;
public class endangered
{
public static void main(String[] param)
{
animal();
System.exit(0);
}
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
for (int i=0; i<=4; i++)
{
while(scan.hasNextInt())
{
array[j] = scan.nextInt();
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
}
}
}

What you can do is sort the array using a built-in method and then retrieve the last value (the greatest) and first value (the smallest).
Arrays.sort(array);
int max = array[array.length - 1];
int min = array[0];
For more on the sort method in Java's Arrays class, here's a description of what it exactly does,
public static void sort(int[] a)
Sorts the specified array into ascending numerical order.
Parameters:
a - the array to be sorted
If you want to get the corresponding animal then I would suggest ignoring the above and use streams in Java 8. Combine the String and int array into one 2D String array. Make the rows equal to the number of animals and the columns equal to 2 (ex: for 5 animals, String[][] array = new String[5][2]). For each row in the 2D array, the first element should be the animal, and the second element should be the size (ex: String [][] array = {{"fox", "1"},{"deer","0"},{"bear", "2"}}). The following will return you a 2D array that is sorted in ascending order and gives you the corresponding animal with it,
String[][] sorted = Arrays.stream(array)
.sorted(Comparator.comparing(x -> Integer.parseInt(x[1])))
.toArray(String[][]::new);
String smallestAnimal = sorted[0][0]; //name of smallest animal
String smallest = sorted[0][1]; //population of smallest animal
String biggestAnimal = sorted[sorted.length - 1][0]; //name of biggest animal
String biggest = sorted[sorted.length - 1][1]; //population of biggest animal

In java 8, you can do something like this:
int min = Arrays.stream(array).reduce(Integer.MAX_VALUE, Math::min);
Update: The user asked for print of the animal as well.
If you need to return the animal as well, it would be best if we edit your code.
We will add 2 more variables. The first one, minVal will contain the lowest number that the user entered. The second one, minValIndex will contain the index of the species with the lowest count.
I removed your while cycle because there was no need for one.
public static void animal()
{
int[] array = new int[5];
int j = 0;
String[] names = {"Komodo Dragon" , "Manatee" , "Kakapo" , "Florida Panther" , "White Rhino"};
System.out.println("Please enter the number of wild Komodo Dragons, Manatee, Kakapo, Florida Panthers and White Rhinos.");
Scanner scan = new Scanner(System.in);
int minVal = Integer.MAX_VALUE;
int minValIndex = -1;
for (int i=0; i<=4; i++)
{
array[j] = scan.nextInt();
if(array[j] < minVal) {
minVal = array[j];
minValIndex = j;
}
int max = array[j];
j++;
if(j==5)
{
System.out.println(array[0] + ", " + names[0]);
System.out.println(array[1] + ", " + names[1]);
System.out.println(array[2] + ", " + names[2]);
System.out.println(array[3] + ", " + names[3]);
System.out.println(array[4] + ", " + names[4]);
}
}
System.out.println("The smallest entered number:" + minVal);
System.out.println("The species:" + names[minValIndex]);
}

You are not calculating max anywhere.
Replace:
int max = array[j]
With:
max = max > array[j] ? max : array[j];
To store the maximum value in the array. (This is a ternary operator)
Now the array have have equal values so in that case take care of this possibility by this code :
for(int i = 0; i <= 4; i++) {
if(array[i] == max) {
System.out.println("Max endangered:" + array[i] + name[i]);
}
}

Related

JAVA array pair for student grades [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
how do I pair the student array with the grade array? When I find the highest grade the corresponding student should also show, and same with the lowest graded student. I cant figure out how to make this program perform as such with two separate arrays.
import java.util.Scanner;
public class Asm7 {
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.println("How many students do you have?: ");
int AMOUNT = 0;
AMOUNT = Scan.nextInt();
String[] STUDENT = new String [AMOUNT];
int COUNTER = 0;
int GRADE [] = new int [AMOUNT];
if (AMOUNT <= 0) {
System.out.println("Invalid student amount");
}
else {
for(int i = 0; i < AMOUNT; i++){
System.out.println("Enter student's first name: " + (i+1));
STUDENT[i] = Scan.next();
System.out.println("Enter student's grade in order added: ");
GRADE[i] = Scan.nextInt();
}
for(int i = 0; i < AMOUNT; i++){
System.out.println(STUDENT[i] + " received the final grade of " + GRADE[i]);}
System.out.println();
int [] Results = MinMax(GRADE);
System.out.println("The highest grade in the class was " + Results[1]);
System.out.println("The lowest grade in the class was "+ Results[0]);
}}
public static int[] MinMax(int[] value) {
int[] Result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int i : value) {
Result[0] = i < Result[0] ? i : Result[0];
Result[1] = i > Result[1] ? i : Result[1];
}
return Result;
}
}
Your while loop validation for number of students is a little late. You want to do this before you declare and initialize your arrays. However, the fact that the while loop was actually used in an attempt towards some form of validation is a really good sign. It's more than most new programmers tend to do. All input should be validated and provide a User the opportunity to supply a correct solution. This can only lead to a smoother, trouble free application and a much better experience for the User. Take a look at this while loop which is in your code:
while (amount < 0) {
System.out.println("Invalid student amount");
}
What is going to happen if the User supplies -1 (this is a valid integer value as is +1)? That's right...your application will end up in an infinite loop spitting out Invalid student amount to the Console Window. Your validation scheme should encompass the entire prompt and then the means to exit it should be more logically defined. With a while loop the best exit is done through its conditional statement, if the condition is false then exit the loop, for example:
Scanner scan = new Scanner(System.in);
// Number Of Students...
String inputString = "";
while (inputString.isEmpty()) {
System.out.print("How many students do you have?: --> ");
inputString = scan.nextLine().trim();
/* Is the supplied Number Of Students valid and within
range (1 to 50 inclusive)? */
if (!inputString.matches("\\d+") || Integer.valueOf(inputString) < 1
|| Integer.valueOf(inputString) > 50) {
// No...
System.err.println("Invalid entry (" + inputString + ") for Student "
+ "amount! Try again...");
inputString = ""; // Empty inputString so we loop again.
System.out.println();
}
}
// Valid amount provided.
int amount = Integer.valueOf(inputString);
String[] student = new String[amount];
int grade[] = new int[amount];
Right away you will notice some obvious changes here. The entire How many students do you have? prompt is contained within a while loop block. If the User does not supply a valid response then that User is asked to try again. The student and grade parallel arrays are declared and initialized only after a valid response for the number of students is provided.
You will also notice that the while loop condition doesn't rely on a integer value but instead it relies on actual string content (regardless of what it is) instead. If the variable is empty ("") then loop again. This is because the Scanner#nextLine() method is used to collect the Users input instead of the Scanner#nextInt() method. The prompt still expects an integer value to be supplied, just a string representation of an integer value and this is validated using the String#matches() method along with a small Regular Expression (regex).
I personally prefer to use the Scanner#nextLine() method for a number of reasons. I personally find it more flexible especially if you want to accept both Alpha and Numerical input from a single prompt. If the prompt above stated:
How many students do you have? (q to quit)
you would just need to add another if statement above the numerical validation code to see if 'q' or 'Q' was supplied, for example:
// If either q or Q is entered then quit application.
if (amountString.matches("[qQ]")) {
System.out.println("Bye-Bye");
System.exit(0);
}
Also, with a good expression passed to the matches() method, there is no need to trap exceptions in order to carry out validations, not that there is anything wrong with this, many people do it, I especially don't however when I have no need to do so.
Side Note: I'm going to state the obvious here and I'm sure you've heard it a hundred times before and you're sick of hearing it but I'm going to tell you again:
Your class methods should start with a lowercase letter (see Java Naming
Conventions).
I know you don't hear the compiler complaining but it does make it a
little more difficult (at times) to read the code. Everyone that reads
your code will appreciate you for it.
Because the student and grade arrays are parallel arrays you would want the minGrade() and maxGrade() methods to return a specific array index value to either the lowest or highest grade so that a referential relationship can be made toward the student that contains that specific grade determined. So, this would be far more useful:
public static int minGrade(int[] arr, int size) {
// Initialize min to have the highest possible value.
int min = Integer.MAX_VALUE;
int returnableIndex = -1;
// loop to find lowest grade in array
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
public static int maxGrade(int[] arr, int size) {
int max = Integer.MIN_VALUE;
int returnableIndex = -1;
// loop to find highest grade in array
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
With everything in play your code might look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Number Of Students...
String amountString = "";
while (amountString.isEmpty()) {
System.out.print("How many students do you have?: --> ");
amountString = scan.nextLine().trim();
// Is the supplied Number Of Students valid and within
// range (1 to 50 inclusive)?
if (!amountString.matches("\\d+") || Integer.valueOf(amountString) < 1
|| Integer.valueOf(amountString) > 50) {
// No...
System.err.println("Invalid entry (" + amountString + ") for Student "
+ "amount! Try again...");
amountString = ""; // Empty inputString so we loop again.
System.out.println();
}
}
// Valid amount provided.
int amount = Integer.valueOf(amountString);
// Declare and initialize parallel arrays
String[] student = new String[amount];
int grade[] = new int[amount];
// Student Names and Grade...
for (int i = 0; i < amount; i++) {
// Student Name...
String name = "";
while (name.isEmpty()) {
System.out.print("Enter student #" + (i + 1) + " name: --> ");
name = scan.nextLine().trim();
/* Is the name valid (contains upper or lower case letters from
A-Z and a single whitespaces separating first and last name?
Whitespace and last name is optional. */
if (!name.matches("(?i)([a-z]+)(\\s{1})?([a-z]+)?")) {
// No..
System.err.println("Invalid Student #" + (i + 1) + " name ("
+ name + ")! Try Again...");
System.out.println();
name = ""; // Empty name so we loop again.
}
}
// Valid Student name provided...
student[i] = name;
// Student Grade...
String gradeString = "";
while (gradeString.isEmpty()) {
System.out.print("Enter student #" + (i + 1) + " grade: --> ");
gradeString = scan.nextLine().trim();
// Is the supplied grade valid and within range (0 to 100 inclusive)?
if (!gradeString.matches("\\d+")
|| Integer.valueOf(gradeString) < 0
|| Integer.valueOf(gradeString) > 100) {
// No...
System.err.println("Invalid entry (" + gradeString + ") for "
+ "Student #" + (i + 1) + " grade! Try again...");
gradeString = "";
System.out.println();
}
}
// Valid Student grade provided...
grade[i] = Integer.valueOf(gradeString);
}
// Display everyone's grade
System.out.println();
for (int i = 0; i < amount; i++) {
System.out.println(student[i] + " received the final grade of " + grade[i]);
}
System.out.println();
//Display who is highest and lowest...
int index = maxGrade(grade, amount);
System.out.println("The highest grade in the class was by '" + student[index]
+ "' with a grade of: " + grade[index]);
index = minGrade(grade, amount);
System.out.println("The lowest grade in the class was by '" + student[index]
+ "' with a grade of: " + grade[index]);
}
public static int minGrade(int[] arr, int size) {
// Initialize min to have the highest possible value.
int min = Integer.MAX_VALUE;
int returnableIndex = -1;
// loop to find lowest grade in array
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
public static int maxGrade(int[] arr, int size) {
int max = Integer.MIN_VALUE;
int returnableIndex = -1;
// loop to find highest grade in array
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
If the data are not sorted, it would be better to find both min and max grades in the same loop, after printing the students and their grades.
Then no loop is needed to print min and max grades:
for (int i = 0; i < amount; i++) {
System.out.println(student[i] + " received the final grade of " + grade[i]);
}
int min = grade[0];
int max = grade[0];
for (int i = 1; i < amount; i++) {
if (grade[i] < min) {
min = grade[i];
} else if (grade[i] > max) {
max = grade[i];
}
}
System.out.println("The highest grade in the class was " + max);
System.out.println("The lowest grade in the class was " + min);
If the index of min/max is sought, it would be possible to print the name of the students who get the min and max grades.
public static void main(String[] args) {
int[] grades = new int[]{50, 51, 52, 50, 60, 22, 53, 70, 60, 94, 56, 41};
int[] result = getMinMax(grades);
System.out.println("Min: " + result[0] + ", Max: " + result[1]);
}
public static int[] getMinMax(int[] values) {
int[] result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int i : values) {
result[0] = i < result[0] ? i : result[0];
result[1] = i > result[1] ? i : result[1];
}
return result;
}
You'll need to handle the case of int[] values being null or empty. You can decide that (Throw an exception, return null... or whatever)

I need to get from the user input random

import java.util.Scanner;
public class hh {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int numbers = input.nextInt();
// Declare an array called numbers with a size of 10
int[] numbers1 = new int[numbers];
insertRandomNumbers(numbers1);
// Print size of numbers
System.out.println("Initial Array: ");
for (int i = 0; i < numbers1.length; i++) {
System.out.print(numbers1[i] + " ");
}
System.out.println("");
//Print First and Last Elements
System.out.println();
System.out.println("First and Last Elements");
int [] lastStep = lastStep(numbers1);
for (int i = 0; i < lastStep.length; i++) {
System.out.print(lastStep[i] + ", ");
}
} // end main
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.get(0);
//last number
int [] lastElement= numbers1.get(numbers1.size()-1);
}
return lastStep;
public static void insertRandomNumbers(int[] x) {
for (int i = 0; i < x.length; i++) {
x[i] = random();
// System.out.print(x[i] + " ");
}
// System.out.println();
}
public static int random() {
int r = 0 + (int) (Math.random() * (101 - 0)) + 0;
return r;
}
My program ask the user to enter a number, then if 10 is entered 10 random numbers are created. With those 10 numbers I need to get the first and last numbers. The way I have my method right now I am getting ERROR: Cannot invoke get(int) on the array type int[]
WHEN I USE
public static int[] lastStep(int[] numbers1) {
//to get first
int [] firstElement= numbers1.array[0];
//last number
int [] lastElement= numbers1.array[numbers1.size()-1];
}
return lastStep;
I get that array cannot be resolved or is not a field
That's because you're using an Array not an ArrayList. Try using numbers1[0] and numbers1[numbers.length - 1]
You should consider changing your lastStep function. From what I can see, it does nothing, because the return statement is outside the function braces. There is also no variable lastStep inside the function that can be returned. Try the following:
public static string firstAndLast(int[] numberArray)
{
return numberArray[0] + ", " + numberArray[numberArray.length - 1];
}
Then just call it like:
System.out.println(firstAndLast(numbers1));
You can't use .get(0) on an array, you have to use array[0].
In your case it would be: numbers1[0]
Use Array List for to add random numbers , then print the last and first one.

Find and Print high number array method Java

What I’m attempting to do is search “gradePsd” array find the highest grade and if there are two grades that are the same value print the name (s) of the students to console.
The problem I’m having is that this method is taking the first index value of the array and printing it because it IS the high value at the first pass and if the second value is larger than the first then it will also print and so on.
So my question is how can I get it to just print the student (s) with the high grade.
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
for (int i = 0; i < gradePsd.length; i++)
{
if (gradePsd[i] >= num)
{
num = gradePsd[i];
nameRtn = NamePsd[i];
}
System.out.print(nameRtn + ", ");
}
}
first find the highest number
then print the students with that number
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
//find the highest number
for (int i = 0; i < gradePsd.length; i++){
if (gradePsd[i] >= num){
num = gradePsd[i];
}
//print students with that number
for (int j = 0; j < NamePsd.length; j++){
if (gradePsd[j] == num)
{
nameRtn = NamePsd[j];
System.out.print(nameRtn + ", ");
}
}
one of possible 1000 solutions.
Initialize num with -1 and take the System.out out of the for loop. But you can only determine one student with your code. You need nameRtn to be a Collection if you want to store more than one name.
Something like this:
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) {
Collection<String> namesRtn = new ArrayList<String>();
int num = -1;
for (int i = 0; i < gradePsd.length; i++) {
if (gradePsd[i] > num) {
num = gradePsd[i];
namesRtn.clear(); // clear name list as we have a new highest grade
namesRtn.add(NamePsd[i]); // store name in list
} else if (gradePsd[i] == num) {
namesRtn.add(NamePsd[i]); // if a second student has the same grade store it to the list
}
}
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn);
}

Sorting the two highest numbers in an array

I'm sorry to ask, but I'm having trouble with an exercise in my book, and I am unsure how to fix it. After entering the student's name and score, I am to find the highest and second highest score. However I cannot find a proper way to find the two highest scores.
The current way I use works, but fails the user enters scores from low to high, such as 70, 80, and 90. If done 90, 80, and 70, it sorts the numbers appropriately.
Is there anything I could change/do/read to put me on the right path?
import java.util.Scanner;
public class StudentSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// For finding highest scores with corresponding array
double firstHighest = 0;
int firstEntry = 0;
double secondHighest = 0;
int secondEntry = 0;
System.out.print("Enter the number of students: ");
int studentCount = input.nextInt();
// Length of arrays set
int[] studentScores = new int[studentCount];
String[] studentName = new String[studentCount];
// Go through loop to set scores and names of each student
for (int i = 0; i < studentCount; i++) {
System.out.print("Enter a student name: ");
studentName[i] = input.next();
System.out.print("Enter a student score: ");
studentScores[i] = input.nextInt();
}
// Find out the highest and second highest scores
// Problem with secondHighest/Entry
for (int i = 0; i < studentScores.length; i++) {
if (studentScores[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = studentScores[i];
firstEntry = i;
} else if (studentScores[i] > secondHighest) {
secondHighest = studentScores[i];
secondEntry = i;
}
}
System.out.println("Top two students: ");
System.out.println(studentName[firstEntry] + "'s score is " + firstHighest);
System.out.println(studentName[secondEntry] + "'s score is " + secondHighest);
}
}
As always, I thank you for any help that you can provide.
It looks like you just forgot to update secondEntry when you get a new highest score. Before the line:
firstEntry = i;
Try adding:
secondEntry = firstEntry;
The problem is here
if (studentScores[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = studentScores[i];
firstEntry = i;
}
you successfully update the values for both secondHighest and firstHighest but you don't fix secondEntry;
you need to add
secondEntry = firstEntry;
before
firstEntry = i;
There are more than 1 ways to solve this problem. The most intuitive way would be akin to picking up a hand of cards (i.e insertion sort). Think of the inputs as a continuous list of cards. It doesn't really matter what order they come in as most players will sort them going from lowest to highest (or the other way around).
So in your input loop:
while(...some_condition_that_ensures_more_input){
//this can be a list for instance, which you keep in order
list = insert_into_correct_place(input);
}
/**
Assuming
a)you sort from lowest to highest
b)there is more than 1 input entered):
*/
highest = list.get(list.length()-1)
second_highest = list.get(list.length()-2)
Another intuitive way (and actually faster) way is to just keep track of two variables:
int [] highest = {Integer.MIN_VALUE(), Integer.MIN_VALUE()};
while(...){
highest = replace_lowest(input, highest);
}
/**
* arr is sorted from lowest to highest : arr[0] is always <= arr[1]
*/
int [] replace_lowest(int input, int [] arr){
//Case 0 : input is less than both the highest 2 numbers
// or is equal to one of them
if (input < arr[0] || input == arr[0] || input == arr[1]) { return arr; }
//Case 1 : input is greater than one of the highest 2, but not both
if (input > arr[0] && input < arr[1]) { arr[0] = input; return arr; }
//Case 2 : input is greater than both of the highest 2 numbers
second_highest = arr[1]; arr[0] = arr[1]; arr[1] = input;
return arr;
}
The first approach is a bit more flexible (it would allow you to pick out X highest numbers instead of just two). The second approach is faster if you know that you will never have to readjust the number of output variables.
You can simply use the java.util.Arrays class and its sort() method. Here's what the code might look like:
Arrays.sort(studentScores);
int firstHighest = studentScores[studentScores.length - 1];
int secondHighest = studentScores[studentScores.length - 2];
Hope this helps.
I wrote you a method with the help of an inner class; it returns an array, the first element is the Student with the heighest score, the second Student the one with the second score.
import java.util.Arrays;
import java.util.Comparator;
public class StudentSort {
static class Student {
Student(int score, String name) {
this.score = score;
this.name = name;
}
int score;
String name;
}
private static Student[] test(int[] studentScores, String[] studentNames) {
Student[] students = new Student[studentScores.length];
for(int i = 0; i < studentScores.length; i++) {
students[i] = new Student(studentScores[i], studentNames[i]);
}
Arrays.sort(students, new Comparator<Student>() {
#Override
public int compare(Student o1, Student o2) {
return new Integer(o1.score).compareTo(o2.score);
}
});
return new Student[]{students[0], students[1]};
}
public static void main(String[] args) {
int[] studentScores = new int[] {5, 9, 7};
String[] studentNames = new String[]{"Jan", "Bert", "Piet"};
Student[] students = test(studentScores, studentNames);
System.out.println("heighest: " + students[0].name + ": " + students[0].score);
System.out.println("second: " + students[1].name + ": " + students[1].score);
}
}

Printing Two Dimensional Array in Special Format

I am working in a small task that allow the user to enter the regions of any country and store them in one array. Also, each time he enters a region, the system will ask him to enter the neighbours of that entered region and store these neighbours.
I did the whole task but I have a small problem:
I could not be able to print each region and its neighbours like the following format:
Region A: neighbour1 neighbour2
Region B: neighbour1 neighbour2
For example, let us take USA map. I want to print the result as following:
Washington D.C: Texas, Florida, Oregon
and so on.
My code is:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test7{public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[] regionNames = new String[REGION_COUNT];
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1)
+ ": ");
regionNames[r] = kb.next();
System.out
.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n)
+ ": ");
regions[r][n] = kb.next();
}
} else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(regionNames[i] +": ");
for (int k = 0; k < 2; k++) {
System.out.print(regions[i][k]+", ");
}
System.out.println();
}
}
}
The code works fine but the problem is with printing the result only.
Also, I should use the 2 dimensional array.
As I see it, you think your problem is dealing with a jagged 2-D array. I think your problem is that you're using arrays of strings in the first place. I'd suggest using a class to model your regions and their neighbors rather than an array of strings.
public class Region
{
private String Name;
public void setName( String name ) {
this.Name = name;
}
public String getName() {
return this.Name;
}
private ArrayList<Region> Neighbors;
public void addNeighbor( Region neighbor ) {
...
}
public ArrayList<Region> getNeighbors()
{
...
}
}
Then keep a hash of the known regions, creating new ones as necessary, and use those to populate a region's neighbors as needed. Then you can iterate over the regions in your hash and, for each region, iterate over its neighbors.
This is what you want:
for (int i = 0; i < region.length; i++){
StringBuilder sb = new StringBuilder();
sb.append(region[i] + ": ");
for (int i2 = 0; i2 < neighbor.length; i2++){
if (i2 != 0 && i2 != neighbor.length-1){
sb.append(", " + neighbor[i2]);
}else{
sb.append(neighbor); //it still need a validation of an array of 2 Strings
}
}
System.out.println(sb.toString());
}

Categories

Resources