/home/caleb/ASDV-Java/Semester 2/Exams/PracticeExam1/src/main/java/com/calebfontenot/practiceexam1/Problem2ArrayObjects.java |
nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java
package com.calebfontenot.practiceexam1;
import java.util.Scanner;
@author
public class Problem2ArrayObjects {
private String[] ;
@return
public static int maxNumberOfColumnsInStringArray(String[] ar)
{
int maxNumberOfColumns = 0;
for (int row = 0; row < ar.length; ++row) {
if (ar[row].length() > maxNumberOfColumns) {
maxNumberOfColumns = ar[row].length();
}
}
return maxNumberOfColumns;
}
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 String[] readNames(int numOfNames)
{
String[] names = new String[numOfNames];
Scanner input = new Scanner(System.in);
for (int i = 0; i < numOfNames; i++) {
System.out.print("Enter a name: ");
names[i] = input.next();
}
return names;
}
@param ar
@return
public static void sortNames(String[] names)
{
for (int i = 0; i < names.length - 1; ++i) {
for (int j = i + 1; j < names.length; ++j) {
char compChar1 = names[i].charAt(0), compChar2 = names[j].charAt(0);
for (int rowIterate = 1; rowIterate < maxNumberOfColumnsInStringArray(names); ++rowIterate) {
if (Character.toLowerCase(compChar1) == Character.toLowerCase(compChar2)) {
try {
compChar1 = names[i].charAt(rowIterate);
compChar2 = names[j].charAt(rowIterate);
} catch (Exception ex) {
if (names[i].length() > names[j].length()) {
System.out.println(names[i].length() + " " + names[j].length());
System.out.println("Swapping " + names[i] + " with " + names[j]);
String temp = names[i];
names[i] = names[j];
names[j] = temp;
}
break;
}
}
if (Character.toLowerCase(compChar1) > Character.toLowerCase(compChar2)) {
System.out.println("Swapping " + names[i] + " with " + names[j]);
String temp = names[i];
names[i] = names[j];
names[j] = temp;
break;
}
}
}
}
}
@param ar
public static void print(String[] arr)
{
for (String string: arr) {
System.out.println(string);
}
}
public static void main(String[] args)
{
int numOfNames = menu();
String[] 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!");
}
}