/home/caleb/ASDV-Java/Semester 2/Exams/PracticeExam1/src/main/java/com/calebfontenot/practiceexam1/Problem1ArrayNames.java |
nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java
package com.calebfontenot.practiceexam1;
import java.util.Arrays;
import java.util.Scanner;
@author
public class Problem1ArrayNames {
public static int maxNumberOfColumnsInJagged2dArray(char[][] ar)
{
int maxNumberOfColumns = 0;
for (int row = 0; row < ar.length; ++row) {
if (ar[row].length > maxNumberOfColumns) {
maxNumberOfColumns = ar[row].length;
}
}
return maxNumberOfColumns;
}
@return
public static int menu()
{
int userInt = -1;
do {
System.out.println("Enter the numbrer of students or -1 to quit: ");
Scanner input = new Scanner(System.in);
userInt = input.nextInt();
if (userInt == 0) {
System.out.println("Input cannot be 0!");
} else {
return userInt;
}
} while (userInt != -1);
return -1;
}
@param numberOfNames
@return
public static char[][] readNames(int numOfNames)
{
char[][] names = new char[numOfNames][];
Scanner input = new Scanner(System.in);
for (int i = 0; i < numOfNames; i++) {
System.out.print("Enter a name: ");
names[i] = input.next().toCharArray();
}
return names;
}
public static String returnRowMajorOrder(char[] ar)
{
String returnString = "";
for (int x = 0; x < ar.length; ++x) {
returnString += ar[x];
}
return returnString;
}
@param ar
public static void sortNames(char[][] names)
{
for (int i = 0; i < names.length - 1; ++i) {
for (int j = i + 1; j < names.length; ++j) {
char compChar1 = names[i][0], compChar2 = names[j][0];
for (int rowIterate = 1; rowIterate < maxNumberOfColumnsInJagged2dArray(names); ++rowIterate) {
if (Character.toLowerCase(compChar1) == Character.toLowerCase(compChar2)) {
try {
compChar1 = names[i][rowIterate];
compChar2 = names[j][rowIterate];
} catch (Exception ex) {
if (names[i].length > names[j].length) {
System.out.println(names[i].length + " " + names[j].length);
System.out.println("Swapping " + returnRowMajorOrder(names[i]) + " with " + returnRowMajorOrder(names[j]));
char[] temp = names[i];
names[i] = names[j];
names[j] = temp;
}
break;
}
}
if (Character.toLowerCase(compChar1) > Character.toLowerCase(compChar2)) {
System.out.println("Swapping " + returnRowMajorOrder(names[i]) + " with " + returnRowMajorOrder(names[j]));
char[] temp = names[i];
names[i] = names[j];
names[j] = temp;
break;
}
}
}
}
}
@param ar
public static void print(char[][] ar)
{
for (char[] nested : ar) {
System.out.println(Arrays.toString(nested));
}
}
public static void main(String[] args)
{
int numOfNames = menu();
char[][] names = null;
while (numOfNames != -1) {
names = readNames(numOfNames);
System.out.println("Original Names:");
print(names);
System.out.println("Sorted Names:");
sortNames(names);
print(names);
numOfNames = menu();
}
System.out.println("goodbye!");
}
}