Student Array menu - java

I'm coding a menu to store names into an array, then giving options to add/delete students and search for a particular student as well, but I cant seem to find out how to set the array so that I can use it in other options, cause, for example, my code only allows me to input names when I use option 1, but it doesnt keep these names in the array when I choose option 3 to search for a name within the array, it just shows up as null for every slot in the array.
Another problem I am having is about how I can delete students, obviously it would be really easy if the name is at the end of the array but what if the name is in the middle, how would I be able to delete the name, shift all the other names down one slot so that there are no gaps in the array?
import java.util.Scanner;
public class Lab10Ex2 {
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p=0;p<20;p++){
if(searchName.equals(stringarray[p])){
x=1;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
}
}while(choice!=5);
}
}

int choice = 0;
int[] stringArray = {};
do{
String[] stringarray = new String[20];
Delete the int[] stringArray line (you don't refer to it anywhere).
Move the String[] stringarray up, outside the loop.
As to deleting, you either have to code that yourself (move everything past the deleted item up one in the array), or use one of the collection classes provided with Java (instead of a native array), which handle deletion for you.

do{
String[] stringarray = new String[20];
On each iteration of your Do { ... } loop, you're recreating the stringarray variable, thus clearing it. If you move this outside of the loop, your student entries will be maintained.
As for deleting, if you're not required to use an array of strings, I would recommend using an ArrayList. It will allow you to easily remove specific entries without worrying about the other entries. Otherwise, yes, the simplest thing to do would be to move all of the other entries down one slot to avoid gaps

Here is the corrected code:
import java.util.Scanner;
public class Lab10Ex2 {
/**
* #param args
*/
public static void main(String[] args) {
int choice = 0;
int[] stringArray = {};
String[] stringarray = new String[20];
do{
System.out.println("----------------MENU---------------");
System.out.println();
System.out.println("1. Add Students");
System.out.println("2. Delete Students");
System.out.println("3. Search for student");
System.out.println("4. Print all Students");
System.out.println("5. exit");
Scanner scanchoice = new Scanner(System.in);
choice = scanchoice.nextInt();
if (choice ==1){
Scanner scannames = new Scanner(System.in);
System.out.println("Please enter the student names into the array");
System.out.println();
int i = 0;
for(i = 0; i<stringarray.length; i++){
String temp =scannames.nextLine();
stringarray[i]=temp.toLowerCase();
if(i==(stringarray.length-1)){
System.out.println("successfully filled up array fully");
System.out.println();
}
}
}
if(choice==2){
}
if(choice==3){
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
}
int x=0;
Scanner scannames1 = new Scanner(System.in);
System.out.println("Enter name of student you want to search for: ");
System.out.println();
String search=scannames1.nextLine();
String searchName=search.toLowerCase();
for(int p = 0; p < stringarray.length ;p++){
if(searchName.equals(stringarray[p])){
x=1;
break;
}
else{
x=0;
}
}
if(x==1){
System.out.println("We have a match in our database for "+ searchName);
}
else if (x==0){
System.out.println("No match for "+ searchName);
}
}
if (choice ==4){
System.out.println("List of names:");
for(int p = 0; p<stringarray.length; p++){
System.out.println(stringarray[p]);
System.out.println();
}
}
}while(choice!=5);
}
}
Things you were doing wrong:
Instantiating the array in the do while loop.
Not breaking out of the loop if a search entity was found in the array.
Use ArrayList if you want to avoid wasting space in arrays after deletion. If you are bound to this with simple arrays, you can do this:
Place null at index from which you deleted.Create a temporary array with same size as the original one with all null values. Copy all the elements from the original array to the temporary one but skip elements that are null. Point the original array to the new array.
AND AVOID HARD CODING ARRAY LENGTHS!

Related

Item in list, but unable to .get() it later

I'm working on a homework problem. Right now, I have a List of names. I have a function that should add the name to the List, and another one that should get it. However, it just gets an empty string
I tried debugging by getting the size() of the array, which increases when I add to it, but I can't get the contents of the item I added (if it's even there)
import java.util.List;
import java.util.Scanner;
public class main
{
public static void main(String args[]) {
List<String> studentNames = new ArrayList<>();
List<List<Integer>> studentScores = new ArrayList<>();
List<String> assignmentNames = new ArrayList<>();
List<Integer> assignmentMaxPoints = new ArrayList<>();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("");
System.out.println("----------------");
System.out.println("1) New Student");
System.out.println("2) Edit Student Name");
System.out.println("3) Delete Student");
System.out.println("4) New Assignment");
System.out.println("5) View Student");
System.out.println("6) View Averages");
System.out.println("----------------");
if (0 != studentNames.size()) {
System.out.println(studentNames);
}
int choice = in.nextInt();
if (choice == 1) {
System.out.println("");
System.out.println("----------------");
System.out.println("Enter the student name:");
System.out.println("----------------");
in.next();
String name = in.nextLine();
studentNames.add(name);
}
if (choice == 2) {
System.out.println("");
System.out.println("----------------");
System.out.println("Enter the old student name:");
System.out.println("----------------");
in.next();
String oldName = in.nextLine();
System.out.println("");
System.out.println("----------------");
System.out.println("Enter the new student name:");
System.out.println("----------------");
in.next();
String newName = in.nextLine();
for (int nameIndex = 0; nameIndex < studentNames.size(); nameIndex++) {
if (studentNames.get(nameIndex).equals(oldName)) {
studentNames.set(nameIndex, newName);
}
}
}
if (choice == 3) {
System.out.println("");
System.out.println("----------------");
System.out.println("Enter the student name:");
System.out.println("----------------");
in.next();
String name = in.nextLine();
for (int nameIndex = 0; nameIndex < studentNames.size(); nameIndex++) {
if (studentNames.get(nameIndex).equals(name)) {
studentNames.remove(nameIndex);
}
}
}
if (choice == 6) {
System.out.println("");
for (int studentIndex = 0; studentIndex < studentNames.size(); studentIndex++) {
System.out.println(studentNames.get(studentIndex));
}
}
}
}
}
I expected the code for the sixth choice to print all the students in studentNames, but it only prints blank lines.
It's not showing anything because of the way you are receiving your input. Let me try to explain. When you write in.next(), the scanner tries to read the word on your input terminal before a space. So lets say you entered Peter as the name of the student, in.next() will read Peter but since you didn't assign it to any variable, it won't be used. Then you did String name = in.nextLine(), this will try to read the input in the nextlline of your terminal, which will be an empty string because you didn't give it any input.
For your code to work. Write
String name = in.next();
Remove
String name = in.nextLine();
It should work now
Note, the size of the array increases because empty strings are being added to it.
You didn't describe your input, but it looks like the problems is in choice 1. you have two calls to scanner, in.next() which returns the first word from the input (until space) and in.readLine() which returns a full line from the input.
To fix just remove the in.next()
For more info you can look at What's the difference between next() and nextLine() methods from Scanner class?

For loop: populate array from user input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was setting up a small app that asks a user to determine the array size and then populate it. The used "for" loop skips the index 0; but I'm uncertain why.
If you run this code with 1 as the array size it skips over the user inputting the first word.
The issue is certainly on the for-loop but it is so simple that I don't see it.
Thanks!
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int arrayDimesion;
Scanner sc = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
arrayDimesion = sc.nextInt();
String[] wordArray = new String[arrayDimesion];
//Populate with user input
for (int i=0; i<arrayDimesion; i++) {
System.out.println("Please enter a word");
wordArray[i] = sc.nextLine();
}
//Print all entered Strings
System.out.println("This are the words you entered: ");
for(int i = 0; i < wordArray.length; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
int r = (int)(Math.random() * wordArray.length);
System.out.println("The random word is: " + wordArray[r]);
}
}
Change your
arrayDimesion = sc.nextInt();
to
arrayDimesion = Integer.parseInt(sc.nextLine());
Reason: sc.nextInt() doesn't consume the newline character that you give after taking arrayDimesion input. This later on gets consumed in the next sc.nextLine() call.
PS: It might throw NumberFormatException. So you can handle it like :
try {
arrayDimesion = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
The below code is clean, easy to read and handles the edge cases.
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int numOfWords;
Scanner scanner = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
numOfWords = Integer.parseInt(scanner.nextLine());
String[] wordArray = new String[numOfWords];
//Populate with user input
System.out.println("Please enter the word(s)");
for (int i = 0; i < numOfWords; i++) {
wordArray[i] = scanner.nextLine();
}
//Print all entered Strings
System.out.println("These are the words you entered: ");
for (int i = 0; i < numOfWords; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
if (numOfWords == 0) {
System.out.println("You didn't enter a word");
} else {
int r = (int) (Math.random() * numOfWords);
System.out.println("The random word is: " + wordArray[r]);
}
}
}

Storing multiple user input in arrays

This program will ask the user for students name and grade then displays both. The values that the user inputs are stored in array names & array grade. I use a counter controlled for loop to gather user input into the arrays. What if I wanted to enter multiple grades for each student??
Fairly new to programming, any input or thoughts would be greatly appreciated on how to do so...
public class Five {
public static void main(String[] args) {
int students;
Scanner input = new Scanner(System.in); //created input scanner
System.out.println("How many students are on your roster? If you wish to exit please type 00: ");// Initializing statement for program************
students = input.nextInt();
if(students == 00) { //Exit program****************
System.out.println("Maybe Next Time!!");
System.exit(0);
}
String[] names = new String[students];// Array names*******
String[]grade = new String[students]; //Array grade********
// Use Counter to go through Array**************************
for(int counter =0; counter < students; counter++){
System.out.println("Enter the name of a student: " + (counter +1));
names [counter] = input.next();
System.out.println("Now enter that students grade A, B, C, D OR F: ");
grade [counter] = input.next();
}
input.close();// End Scanner object
//Use For loop for Printing names and grades entered by the user**************
System.out.println("Your students names and grades are as follows: ");
for(int counter =0; counter < students; counter++){
System.out.println("Name: " + names[counter]);
System.out.println("Grade: " + grade[counter]);
}
}
}
You could use a ragged array for the grades to enter more than one
You would need to declare it so here is a way to do that.
String[] names = new String[students];// Array names*******
String[][]grade = new String[names][]; //Array grade********
for(int i=0; i<names[i];i++)
{System.out.println("How many grades will you enter for "+names[i]+"?")
int temp=input.nextInt();
for(int j=0; j<names[i][temp-1];j++){
grad[i][j]=input.next();
}}
You should probably make a Student class and a Grades class and store them as objects. Using a data structure your best choice is a hashmap.
HashMap<String, List<String>> grades = new HashMap<>();
grades.put("Jack", new ArrayList<>());
grades.get("Jack").add("A");
You can find out more about HashMap here

Java problems creating a new node

• Ask the user to enter a set of 5 numbers.
• For each number entered, add it into the front of the linked list.
• Now, ask the user to enter a search number.
• Using a for loop or while loop, search whether the number exist in one of the Nodes in the linked list.
• If there is a matching node, create a new node with data 88 and insert it right before the matching node. Otherwise, display the message “No such number”.
Hi everyone, I would like you to help me with the java code for the last part.
public static void main(String[] args) {
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt(); sc.nextLine();
for(int i = 0; i < 4; i++){
list.addFront(num);
}
System.out.print("Enter a number: ");
int search = sc.nextInt(); sc.nextLine();
for(Node j = list.getHead(); j!= null; j=j.getNext()){
if((Integer)j.getData()==search){
list.addNode();
}else{
System.out.println("No such number");
}
}
public static Node addNode(T n);//???
}
I think your code will not even work for the first point. What you do is read a number once and then put the same number 4 times into the linked list.
For adding the node to the list before another node you need the index of the node where you want to put it in front of and then use the add(int index, E element) mehtod of the LinkedList. The index can be found by indexOf(Object o).
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
Re factored your code.Here is a working solution.You don't need to create an additional function for addNode().
There is a predefined function known as add(index,element) when you are using java.util.LinkedList.But i would advice to first create your own linklist instead of using predefined LinkedList class.
This will clear all your doubts.
Here i am assumming you are using java.util.LinkedList.
public static void main(String args[]){
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 4; i++)
{
System.out.println("Enter a number: ");
int num = sc.nextInt(); sc.nextLine();
list.addFirst(num);
}
System.out.print("Initial list:"+list);
System.out.print("Enter a number: ");
int search = sc.nextInt(); sc.nextLine();
Iterator<Integer > itr=list.iterator();
int i=0;
boolean flag=false;
while(itr.hasNext())
{
int data=itr.next();
if(data==search){
list.add(i,88);
flag=true;
break;
}
i++; //index of data
}
if(!flag)
{
System.out.println("No such number");
}
else
{
System.out.println("Number inserted at "+i);
}
System.out.print("final list:"+list);
sc.close();
}
Hope it helps you.

ArrayList and strings

I have this question Write a static method which takes an ArrayList of Strings and an integer and changes the ArrayList destructively to remove all Strings whose length is less than the integer argument. i have this code so far could someone explain where I'm going wrong. it compiles but it doesn't remove any strings from the array list.
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
}
}
System.out.println("The ArrayList is "+a);
}
}
When you remove an item of the ArrayList be sure to decrement "j". Also, although it is not common, set the for-condition to j < a.size(). Otherwise create a separate variable to store the size before the loop and then decrement it as well.
The following code should work.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<a.size(); j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
j--;
}
}
System.out.println("The ArrayList is "+a);
}
You traverse the list from left to right and remove items as you go along. This causes a problem when removing multiple items, because the indices don't match any more.
This can be fixed quite easily by traversing the list from end to begin, instead of from begin to end.
Because now, if you remove an item, this doesn't affect the items to be removed later on:
for (int j = words.length - 1; j >= 0; j--)
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static ArrayList<String> a;
public static ArrayList<String> presenter;
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
a = new ArrayList<String>();
presenter = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if((b.length()<len))
{
//do nothing
}
else
{
presenter.add(a.get(j));
}
}
System.out.print("The ArrayList is " + presenter);
}
}
This is an alternative since you said the other codes didn't work, I simply transferred the "Good" data to another arraylist and printed out that one.

Categories