I have a homework question from college that I am having trouble with and I was wondering if anyone could give me some advice on where to go with it. We are using Arrays, for loops, if else and Strings.
I have to create a programme to take in a number of peoples names then put them in an Array ( which I had no problem with) I then need to separate the names in the array according to the first letters of each name : AG in one array, letters HP in another and the rest in a final array.
I have been told to use a String Function for this but not to use lists or Char. This is the code I have so far :
import java.util.Scanner;
public class Party {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); // declaring scanner
int numGuests; // declaring the variable for number of guests
System.out.println("please enter the number of guests you are hosting : ");
numGuests = sc.nextInt(); // scanner for user inout num of guests
String[] names = new String[numGuests]; // string for number of guests
System.out.println("Please enter names ");
for(int i = 0; i < names.length; i++) // for loop for inputing the names.
{
names[i] = sc.next();
}
}
}
Please Use below logic and get result according to your requirement..
package com.test;
public class Namessplite {
public static void main(String args[]){
String[] names={"ABC","CAD","JKL","MNO"}; // these are names for example
String[] atog_group = new String[10];
String[] gtopgroup= new String[10];
int j=0,k=0;
for(int i=0;i<names.length;i++){
if((int)names[i].charAt(0)<72 && (int)names[i].charAt(0)>64){
atog_group[j]=names[i];
j++;
}else{
gtopgroup[k]=names[i];
k++;
}
}
System.out.println("A TO G Names Are :: ");
for(int m=0;m<j;m++){
System.out.println(atog_group[m]);
}
System.out.println("G TO P Names Are :: ");
for(int m=0;m<k;m++){
System.out.println(gtopgroup[m]);
}
}
}
Java 8 Style:
private static void splitNamesToArray(String[] names) {
String[] aToG = Arrays.stream(names).filter(n -> n.toUpperCase().charAt(0) >= 65 && n.toUpperCase().charAt(0) <= 71).toArray(String[]::new);
String[] hToP = Arrays.stream(names).filter(n -> n.toUpperCase().charAt(0) >= 72 && n.toUpperCase().charAt(0) <= 80).toArray(String[]::new);
String[] rest = Arrays.stream(names).filter(n -> n.toUpperCase().charAt(0) >= 81 && n.toUpperCase().charAt(0) <= 90).toArray(String[]::new);
System.out.println("A to G: " + Arrays.toString(aToG));
System.out.println("H to P: " + Arrays.toString(hToP));
System.out.println("Rest: " + Arrays.toString(rest));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.