Java String function help needed - java

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 : A-G in one array, letters H-P 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));
}

Related

Can I search for values in two different type of arrays with just one type of variable?

I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!

Why do I always get to enter a-1 strings in this string array?

Why do I always get to enter a-1 strings in this string array?
public class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Declare the variable
int a;
// Read the variable from STDIN
a = in.nextInt();
String strs[]=new String[a];
for(int i=0;i<a;i++)
strs[i]=in.nextInt();
}
}
You can change condition in your loop, like this :
for (int i = 0; i < a - 1; i++) {
strs[i] = in.nextInt();
}
You are iterating correctly a number of times equal to a. Not a-1. So the question appears to be invalid:
public class Source {
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
// Declare the variable
int a;
System.out.print("How many Strings would you like to enter? ");
// Read the variable from STDIN
a = in.nextInt();
String[] strs = new String[a]; // this will fail for certain values of `a`
for(int i=0; i<a; i++) {
System.out.format("Enter String number %d: ", i+1);
strs[i]= in.next();
}
System.out.println("Result: " + Arrays.toString(strs));
}
}
}
run:
How many Strings would you like to enter? 2
Enter String number 1: Apple
Enter String number 2: Pen
Result: [Apple, Pen]

How to get array of strings or integers from users inside looping statement?

When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}

Java - Storing userinput using Arrays and Methods

I am trying to ask the user to enter 10 names using arrays, and then return the method. Any help would be appreciated. Thanks in advance.
import java.util.Scanner;
public class methodbankinput
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
String[] names = {};
printarray(names);
}
public static void printarray(String[] names)
{
for (int i = 1; i < 11; i++)
{
System.out.println("Please enter 10 names" + i);
names = kb.nextLine();
}
}
}
This code won't compile. You've defined Scanner kb in your main and you can't see it inside printarray.
You've also declared a 0-length array. I don't think that's what you want.
And to store something in an array, you need to specify what index you want to store the value in. Arrays are also zero-indexed so i should start at 0, as so.
for (int i = 0; i < names.length; i++) // You could use i < 10 as well
{
System.out.println("Please enter 10 names" + i);
names[i] = kb.nextLine();
}

method cannot be applied to given types / cannot find symbol

I can't seem to get past this error. My code:
import java.util.*;
public class Collector {
public static void Names () {
java.util.Scanner input = new java.util.Scanner(System.in);
// Prompt the user to enter the number of students
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
// Create arrays
String[] names = new String[numberOfStudents];
double[] scores = new double[numberOfStudents];
// Enter student name and score
for (int i = 0; i < scores.length; i++)
{
System.out.print("Enter student's name: ");
names[i] = input.next();
System.out.print("Enter student's exam score: ");
scores[i] = input.nextDouble();
System.out.println(" ");
}
}
void SortRoutine (String[] names, double[] scores) {
for (int i = scores.length - 1; i >= 1; i--)
{
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++)
{
if (currentMax < scores[j])
{
currentMax = scores[j];
currentMaxIndex = j;
}
}
//arrange values as necessary
if (currentMaxIndex != i)
{
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
}
// Print student data
System.out.println(" ");
System.out.println("***** Student Scores Sorted High to Low *****");
System.out.println(" ");
for (int i = scores.length - 1; i >= 0; i--)
{
System.out.println(names[i] + "\t" + scores[i] + "\t");
}
System.out.println(" ");
}
}
Main Method:
import java.util.*;
import java.util.Arrays;
public class NameCollector {
public static void main(String[] args) {
Collector collect = new Collector();
collect.Names();
collect.SortRoutine();
}
}
If I remove the arguments from line 28 of the Collector class I get cannot find symbol errors. Which I believe means that Jcreator can't find the array values. How would I go about making the array values defined in my first method visible to the second? If I leave the arguments in line 28 the error message is:
C:\Users\Dark Prince\Documents\JCreator LE\MyProjects\NameCollector\src\NameCollector.java:16: error: method SortRoutine in class Collector cannot be applied to given types;
collect.SortRoutine();
^
required: String[],double[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Process completed.
I'm thinking I should not use the arguments and make it so the array values can be seen by the sorting method, but really I just want the darn thing to work.
You asked: How would I go about making the array values defined in my first method visible to the second?
There's plenty of ways to do this. This is one way of doing it (probably not the best):
You can turn the arrays into static instance members in the Collector class like this:
public class Collector {
static String[] names;
static double[] scores;
public static void Names () {
And then when you create the arrays in the Names method you'd do this:
// Create arrays
names = new String[numberOfStudents];
scores = new double[numberOfStudents];
And finally you change the method signature for SortRoutine from:
void SortRoutine (String[] names, double[] scores)
to
void SortRoutine ()

Categories