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

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?

Related

How to give each student a unique ID after being created by the user on JAVA program

I am working on a school project that basically allows the user to create, edit or view students. Once a student is created, they each get assigned a unique ID like 1, 2, 3, etc. All the functionally of creation, editing and displaying is working but I am stuck on have to give them a unique ID after created. Here is the code I have and in the // commented areas is what I attempted to do but I am not sure if its right. Any ideas will be very appreciated.
import java.util.Scanner;
import java.io.*;
public class MidTermProject {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Here is the sample of menu choices for Main Menu.");
System.out.println("\nWelcome to University Enrollment" + "\n1. Create Student" + "\n2. Edit Student" + "\n3. Display Student" + "\n0. --- Quit ---");
System.out.println("Please enter a valid choice(1-10, 0 to Quit) :");
int userInput = keyboard.nextInt();
if(userInput == 1) {
CreateStudent();
} else if(userInput == 2) {
EdithStudent();
} else if(userInput == 3) {
DisplayStudent();
} else if(userInput == 0) {
System.out.print("Done");
} else {
System.out.println("Invalid Option, Please try again.");
userInput = keyboard.nextInt();
if(userInput == 1) {
CreateStudent();
} else if(userInput == 2) {
EditStudent();
} else if(userInput == 3) {
DisplayStudent();
} else if(userInput == 0) {
System.out.print("Done");
}
}
}
public static void CreateStudent() throws IOException {
String FullName;
String address;
String city;
String state;
int StudentID;
Scanner keyboard = new Scanner(System.in);
FileOutputStream fstream =
new FileOutputStream("StudentInfo.dat");
DataOutputStream outputFile =
new DataOutputStream(fstream);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
outputFile.writeUTF(FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
outputFile.writeUTF(address);
System.out.print("City: ");
city = keyboard.nextLine();
outputFile.writeUTF(city);
System.out.print("State: ");
state = keyboard.nextLine();
outputFile.writeUTF(state);
//allowed the user to select their own ID number
System.out.print("Please get a Student ID(1-10): ");
//Store the selected number on StudentID
StudentID = keyboard.nextInt();
//The for loop will increment index each time a user is created
for(int index = 0; index == StudentID; index++) {
//The if statement will compare index and StudentID, if equal will ask the user to enter a different number
if(index == StudentID) {
System.out.print("The selected ID has been selected already, Please select a different ID");
StudentID = keyboard.nextInt();
}
}
//write the number in the file
outputFile.writeInt(StudentID);
System.out.print("Successfully Created");
}
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
Scanner keyboard = new Scanner(System.in);
RandomAccessFile file =
new RandomAccessFile("StudentInfo.dat", "rw");
file.seek(0);
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
file.writeUTF(editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
file.writeUTF(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
file.writeUTF(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
file.writeUTF(editState);
file.close();
System.out.print("Successfully Edited");
}
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
DataInputStream inputFile = new DataInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = inputFile.readUTF();
System.out.print(student + " ");
}
catch (EOFException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}
Firstly, following Java naming conventions makes your code more readable. So use lowercase first when naming a variable: studentId rather than StudentId. Initial-caps is for class names.
In your create student method, your for loop makes no sense.
for(int index = 0; index == StudentID; index++) {
//The if statement will compare index and StudentID, if equal will ask the user to enter a different number
if(index == StudentID) {
System.out.print("The selected ID has been selected already, Please select a different ID");
StudentID = keyboard.nextInt();
}
}
A for loop simply increments the index defined in the first clause, stepping the increment according to the third clause, until the second clause proves true.
So in your code, if the user enters 4, your loop counts 0, 1, 2, 3, 4 «bingo». Now that we reached the user’s specified number, we go on to ask them for another number. And we’re done. But that process is illogical.
That code fails to accomplish your goal of checking for existing students. You need to review all existing students one-by-one. Compare each existing student ID against the desired ID. Only after exhausting the list of all known students should we use the desired ID. If we find a match on an existing student, then we break out of the loop to ask the user for another choice of ID. And we need another outer loop to continue this “ask, search, ask again if needed” process until an unused desired ID is determined.
Big tip: If you write out your problem statement and solution attempt as plain prose, similar to what I just did in the paragraph above, your programming will go more smoothly. And your written prose will be fodder for writing helpful comments in your source code.

Why can't I enter another string after the first time in a for loop?

I want to create a program that allows me to enter name, age, and year of birth for 5 different people. However, I get a problem where I cannot enter another name after I entered the first in my for loop. Here is my code:
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
}
}
The program works fine when I run it, but it will not allow me to enter the other 4 names after I entered the first. Here is the output I am getting:
Please note:
String java.util.Scanner.next() - Returns:the next token
String java.util.Scanner.nextLine() - Returns:the line that was skipped
Change your code [do while initial lines] as below:
names[i] = keyboard.next();
Take a look- I've fixed your code- added "keyboard.nextLine();" at the end.
public static void main(String[] args) {
String[] names = new String[5];
int[] s = new int[5];
Scanner keyboard = new Scanner (System.in);
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
names[i] = keyboard.nextLine();
System.out.print("Age: ");
s[i] = keyboard.nextInt();
System.out.print("Year: ");
s[i] = keyboard.nextInt();
keyboard.nextLine();
}
}
The reason you need to add it is that "nextInt()" will only read what you've entered and not the rest of the line. What's left of the line will be then read by "names[i] = keyboard.nextLine();" automatically.
By putting another "keyboard.nextLine()" at the end, I've skipped what left of the line and then "names[i] = keyboard.nextLine();" gets a new line to read input from.
Every beginner in Java encounters this problem sooner or later :)

java array that accepts input of put name mark, quit and get name (not working)

im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 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;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}

Student Array menu

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!

Cannot Store Data into ArrayLists?

thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}

Categories