Trying to make a program, but struggling with delete option - java

if I choose option 3 on this program, I would like it to delete one of the exam grades.
The program outputs like this at the moment if option 2 (view grades) is chosen:
1) Bob Jones, Comp, 18
2) Matt Jones, computing, 100
3) Adam Frank-Jones, Drama, 69
As you can see in the code, the numbers incrementing down the side are represented by "i". What I'm looking for is if I enter "1" for example when choosing a row to delete, it deletes a row (in this case "1) Bob Jones, Comp, 18"). A row is made up of i + First Name + Surname + Course + Mark, all concatenated together.
Now, I have looked around the internet on code helping me do delete an entry. I have tried if i equals user input, then delete. I have tried using a temporary file where the user searches by first name (I am unsure how to code this though") and then writes back to original using BufferedWriter etc. I have been unsuccessful on making this work though.
Can anyone help me? Thanks
Code:
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[] args) throws Exception {
BufferedReader reader = null;
FileWriter grades = new FileWriter("grades2.txt",true);
BufferedWriter bw = new BufferedWriter(grades);
PrintWriter out = new PrintWriter(bw);
Scanner scan = new Scanner(System.in);
int examMark = 0;
String firstName = "";
String surName = "";
String course = "";
String entry = "";
String firstCap = "";
String surCap = "";
int menu =0;
System.out.println("Welcome to the 'GradeEnter' program! ");
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Grade(s)");
System.out.println("4) Exit");
menu = scan.nextInt();
switch (menu) {
case 1:
System.out.print("Please enter student first name: ");
firstName = scan.next();
while(!firstName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid first name: ");
firstName = scan.next();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.print("Please enter student surname: ");
surName = scan.next();
while(!surName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid surname: ");
surName = scan.next();
}
surCap = surName.substring(0,1).toUpperCase() + surName.substring(1);
System.out.print("Please select student course: ");
course = scan.next();
System.out.print("Please enter student mark: ");
while (!scan.hasNextInt())
{
System.out.print("Please enter a valid mark: ");
scan.next();
}
examMark = scan.nextInt();
if (examMark < 40)
{
System.out.println("Failed");
}
else if (examMark >= 40 && examMark <= 49)
{
System.out.println("3rd");
}
else if (examMark >= 50 && examMark <= 59)
{
System.out.println("2/2");
}
else if (examMark >= 60 && examMark <= 69)
{
System.out.println("2/1");
}
else if (examMark >= 70 && examMark <= 100)
{
System.out.println("1st");
}
else
{
System.out.println("Invalid Mark");
}
entry = (firstCap + " " + surCap + ", " + course + ", " + examMark);
out.println(entry);
break;
case 2:
File file = new File("grades2.txt");
reader = new BufferedReader(new FileReader(file));
int i =1;
String line;
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
break;
case 3:
// HERE
break;
case 4:
System.out.println("Thanks for using 'GradeEnter' ");
System.exit(0);
break;
}
out.close();
scan.close();
}
}

Related

How to show only the grades

I made the invalid grades into " " but it seems in output it's showing space like this https://i.stack.imgur.com/3kHZW.png how to show only the valid grades? the invalid grades is making blank space in output
This is the question https://i.stack.imgur.com/uxLhG.png
This is the needed output https://i.stack.imgur.com/HNZpZ.png
This is my Program
String [][] student = new String[100][3];
int stu = 0, totalp=0, totalf=0;
for(int h=0; h<100; h++) {
System.out.print("Enter Name: ");
student[h][0] = sc.nextLine();
System.out.print("Enter Grade: ");
student[h][1] = sc.nextLine();
int grade = Integer.parseInt(student[h][1]);
if(grade >100 || grade <50) {
student[h][0] = "";
student[h][1] = "";
student[h][2] = "";
System.out.println("Invalid Grade");
}
else if(grade >=75) {
student[h][2] = ("Passed");
totalp++;
}
else if(grade <=74) {
student[h][2] = ("Failed");
totalf++;
}
System.out.print("Add new record (Y/N)?: ");
char choice = sc.nextLine().charAt(0);
System.out.println("");
if(choice == 'y' || choice =='Y') {
stu++;
continue;
}
else if(choice == 'n' ||choice =='N') {
break;
}
}
System.out.println("\nGRADE SUMMARY REPORT");
System.out.println("\nName\tGrades\tRemarks");
for(int i =0; i<stu+1; i++) {
for(int h =0; h<student[i].length; h++) {
System.out.print(student[i][h] + "\t");
}
System.out.println();
}
System.out.println("\nTotal Passed: " + totalp);
System.out.println("Total Failed: "+ totalf);
If a grade entered by the user is invalid, just don't add it to student array. Then it won't get printed at all. You should also handle the case where the user does not enter a number when asked to enter a grade.
When asking the user if she wants to add a new record, you only need to check whether she entered a Y. Anything else can be considered a no.
The below code uses method printf to format the report. Also, in order to format the report, I keep track of the longest name entered by the user.
import java.util.Scanner;
public class Students {
private static final int MAX_ROWS = 100;
private static final int NAME = 0;
private static final int GRADE = 1;
private static final int REMARK = 2;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String[][] student = new String[MAX_ROWS][3];
int totalp = 0, totalf = 0, longest = 0;
int h = 0;
while (h < MAX_ROWS) {
System.out.print("Enter Name: ");
String name = sc.nextLine();
int len = name.length();
if (len > longest) {
longest = len;
}
System.out.print("Enter Grade: ");
String grade = sc.nextLine();
try {
int mark = Integer.parseInt(grade);
if (mark >= 50 && mark <= 100) {
student[h][NAME] = name;
student[h][GRADE] = grade;
if (mark >= 75) {
student[h][REMARK] = "Passed";
totalp++;
}
else {
student[h][REMARK] = "Failed";
totalf++;
}
h++;
if (h == MAX_ROWS) {
System.out.println("Maximum students entered.");
}
else {
System.out.print("Add new record (Y/N)?: ");
String choice = sc.nextLine();
if (!"Y".equalsIgnoreCase(choice)) {
break;
}
}
}
else {
throw new NumberFormatException();
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Invalid. Grade is a number between 50 and 100.");
}
System.out.println();
}
System.out.println("\nGRADE SUMMARY REPORT\n");
if (longest < 4) {
longest = 4;;
}
System.out.printf("%-" + longest + "s", "Name");
System.out.println(" Grade Remarks");
String format = "%-" + longest + "s %4s %s%n";
for (int i = 0; i < h; i++) {
System.out.printf(format, student[i][NAME], student[i][GRADE], student[i][REMARK]);
}
System.out.println();
System.out.println("Total passed: " + totalp);
System.out.println("Total failed: " + totalf);
}
}
Here is output from a sample run of the above code:
Enter Name: Superman
Enter Grade: 99
Add new record (Y/N)?: y
Enter Name: Batman
Enter Grade: 23
Invalid. Grade is a number between 50 and 100.
Enter Name: Iron Man
Enter Grade: 74
Add new record (Y/N)?: n
GRADE SUMMARY REPORT
Name Grade Remarks
Superman 99 Passed
Iron Man 74 Failed
Total passed: 1
Total failed: 1
You may also want to refer to the Exceptions lesson in Oracle's Java tutorials.
right now you are still printing the invalid grades in a line. what you want is to check and make sure the grade is valid before printing it. Since you made all the invalid grade an empty string, you can simply check for that like so
if(!student[i][h].isEmpty()){
System.out.print(student[i][h] + "\t");
}

Creating a loop from Java input

I need to create a loop from user input. For example they have to enter how many times they want to shuffle the cards. And then it will run the loop of the cards being drawn as many times as the user input states. I will apply my entire code.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class stringVariables {
private static boolean isValid;
public static void main (String[]args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner user_input = new Scanner (System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next ();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next ();
String full_name;
full_name = first_name + " " + last_name;
System.out.println( full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
if(num1 + num2 + num3 == 31){
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
}
else
System.out.println("Better Luck Next Time");
//the play again menu. this blocks any input besides 1 or 0
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch=Integer.parseInt(br.readLine());
}
}}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}
what I need to do is loop the user input from
boolean testing = false;
String pos = "";
while(true)
{
testing = false;
Scanner sc = new Scanner(System.in);
System.out.println("How many times do you want the numbers shuffled: ");
pos = sc.next();
for(int i=0; i<pos.length();i++)
{
if(!Character.isDigit(pos.charAt(i)))
testing = true;
}
if(testing == true)
{
System.out.print("Enter only numbers.. ");
continue;
}
else
{
int key = Integer.parseInt(pos);
break;
And make it replay this loop
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Random rn = new Random();
int ch=1;
while(ch==1){
// get two random numbers between 7 and 13
Random r = new Random();
int num1 =7 + (int)(Math.random()*(7));
int num2 = 7 + (int)(Math.random()*(7));
int num3 = 7 + (int)(Math.random()*(7));
System.out.println(num1 + " + " + num2 + " + " + num3+ " = " + (num1 + num2 + num3 ));
int i = 0 ;
{
System.out.println( num1 + num2 + num3 );
i++ ;
}
To make it loop to the desired user input after the completion of their name
Although it's not entirely clear what you're trying to achieve I have tried to modify your code from your original post to make it more readable and function the way you want. Please see my comments in the code below, I tried to prefix all of my comments with "EDIT" so you could easily identify which are mine.
//EDIT: added new import to help with validating user input
import java.util.InputMismatchException;
import java.util.Scanner;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.BufferedReader;
import java.io.IOException;
//EDIT: removed import that is no longer needed, see code changes below
//import java.io.InputStreamReader;
import java.util.Random;
//EDIT: changed class name to java standard naming convention using uppercase for first letter.
public class StringVariables {
// EDIT: this variable is not used, I removed it
// private static boolean isValid;
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
// is not inputed
// EDIT: removed this variable as it is no longer used in the code that
// follows.
// boolean testing = false;
// EDIT: Removed this variable in favor of using Scanner.nextInt() in
// the code below
// String pos = "";
// EDIT: Added this variable and initialized to an invalid value so that
// we can loop until a valid value is entered.
int numShuffles = -1;
while (numShuffles < 0) {
// EDIT: This variable is not needed with the new logic
// testing = false;
// EDIT: This is not needed, you already have a Scanner object above
// called user_input
// Scanner sc = new Scanner(System.in);
System.out
.println("How many times do you want the numbers shuffled? ");
try {
// EDIT: modified the lines below to fix infinite loop, forgot
// about certain Scanner behavior so switched back to
// Integer.parseInt
String inputText = user_input.next();
numShuffles = Integer.parseInt(inputText);
} catch (NumberFormatException inputException) {
System.out.print("Please enter a valid number. ");
}
} // EDIT: added closing bracket here
// EDIT: none of the code commented out below is needed when using
// the new code above.
// for(int i=0; i<pos.length();i++)
// {
// if(!Character.isDigit(pos.charAt(i)))
// testing = true;
// }
// if(testing == true)
// {
// System.out.print("Enter only numbers.. ");
// continue;
// }
//
// else
// {
// int key = Integer.parseInt(pos);
//
//
// break;
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(2000);
System.out
.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// EDIT: rather than repeating the same code over and over just use a
// loop if you want to print 25 blank lines.
for (int i = 0; i < 25; i++)
System.out.println(" ");
// EDIT: see previous comment, removed duplicate code
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
// System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
// EDIT: This BufferedReader is not needed with changes to code below
// BufferedReader br = new BufferedReader(new
// InputStreamReader(System.in));
Random random = new Random();
// EDIT: removed the following two lines to simplify the looping logic
// int ch = 1;
// while (ch == 1) {
while (true) {
// EDIT: your comment is wrong, you're creating 3 numbers here not 2
// get two random numbers between 7 and 13
// EDIT: no need to create a new Random inside the loop, you can
// re-use a single instance.
// Random r = new Random();
// EDIT: This approach is fine, but I think using the Random class
// is easier to read so I replaced your code with code that uses
// Random
// int num1 = 7 + (int) (Math.random() * (7));
// int num2 = 7 + (int) (Math.random() * (7));
// int num3 = 7 + (int) (Math.random() * (7));
// EDIT: based on your replies it seems like you want to give the user
// several changes for each run of the game and this is what you meant
// by "shuffle". I have implemented that feature below with the for loop.
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
+ (num1 + num2 + num3));
// EDIT: you never use the variable i so I removed this code.
// int i = 0;
// {
// System.out.println(num1 + num2 + num3);
// i++;
// }
if (num1 + num2 + num3 == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
}
}
if (!isWinner)
System.out.println("Better Luck Next Time");
// the play again menu. this blocks any input besides 1 or 0
// EDIT: again, re-use the existing scanner
// Scanner sc = new Scanner(System.in);
// EDIT: There is a much simpler and easier-to-read way to do this
// so I have removed your code and added new code after.
// EDIT: Also this code does not work correctly, it fails to exit
// properly when the user enters a letter.
// while (true) {
// System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
// String input = user_input.next();
// int intInputValue = 0;
// try {
//
// intInputValue = Integer.parseInt(input);
// Integer.parseInt(input);
// break;
// } catch (NumberFormatException ne) {
// System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
//
// ch = Integer.parseInt(br.readLine());
// }
//
// }
// EDIT: here is the new code, see previous comment.
System.out
.println("Do you want to play again? (If you do enter y or yes) ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// EDIT: close the scanner when you're finished with it.
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
Why not just use
while(true) {
try{
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
for(int i = 0; i < pos; i++) {
//do the shuffling
}
I have done some altering in your code and I feel this is what you are looking for. Just copy paste the code and it should work ideally.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException, IOException {
//user inputs their name in this section
Scanner sc = new Scanner(System.in);
String first_name;
System.out.print("Enter Your First Name: ");
first_name = sc.next();
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = sc.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
//this is the shuffle portion as well as something to see if a number is not inputed
int ch = 1;
while (ch == 1) {
int pos = 0;
System.out.println("How many times do you want the numbers shuffled: ");
while (true) {
sc = new Scanner(System.in);
try {
pos = sc.nextInt();
break;
} catch (InputMismatchException e) {
System.out.println("Use only numbers.");
}
}
// we are now going to generate their random number and add a delay after completing their name fields
delay(2000);
System.out.println(" You will be given a hand of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/* end of explanation of the game, next i will create a new screen
with the user's name and numbers */
delay(4000);
for (int i = 0; i < 100; i++) {
System.out.println(" ");
}
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num1 = 0, num2 = 0, num3 = 0;
boolean isWinner = false;
for (int j = 0; j < pos; j++) {
num1 = 7 + (int) (Math.random() * (7));
num2 = 7 + (int) (Math.random() * (7));
num3 = 7 + (int) (Math.random() * (7));
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
if (num1 + num2 + num3 == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
isWinner = true;
}
}
if(!isWinner){
System.out.println("Better Luck Next Time");
}
//the play again menu. this blocks any input besides 1 or 0
while (true) {
System.out.println("Want To Play Again ? ANY # = YES, ANY LETTER = NO");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, type 1 to continue, or any letter to quit");
ch = Integer.parseInt(br.readLine());
}
}
}
}
//delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
//delay field
}
}
}

Beginner Java: Understanding error message: Exception in thread "main" java.util.NoSuchElementException

I am very new to Java and I'm having trouble understanding the errors I get from these classes. Even though I have searched it up throughout stackoverflow and various other sites, I am not able to grasp the meaning of them. Any help would be great in understanding these errors messages.
Main Class
import java.io.IOException;
import java.util.Scanner;
public class Assignment4 {
public static void main (String[] args) throws IOException{
int command = 0;
Scanner kb=new Scanner(System.in);
System.out.print("Enter the name of the input file:Enter data.txt: ");
String fileName=kb.next();
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
prompt();
System.out.print("Enter a command: ");
String ans=kb.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("a") ||ans.equalsIgnoreCase("add") ||
ans.equalsIgnoreCase("sa") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("sn") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("s") || ans.equalsIgnoreCase("save") ||
ans.equalsIgnoreCase("c1") || ans.equalsIgnoreCase("change1") ||
ans.equalsIgnoreCase("c2") || ans.equalsIgnoreCase("change2") ||
ans.equalsIgnoreCase("c3") || ans.equalsIgnoreCase("change3") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (command)
{
case 1: cr.add();
break;
case 2: cr.sortAverage();
cr.display();
break;
case 3: cr.sortNames();
cr.display();
break;
case 4: cr.remove();
cr.display();
break;
case 5: cr.save();
cr.display();
break;
case 6: ClassRoll.changeScore1();
cr.display();
break;
case 7: ClassRoll.changeScore2();
cr.display();
break;
case 8: ClassRoll.changeScore3();
cr.display();
break;
case 9: Student s=cr.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 10: cr.display();
break;
case 11 : System.out.println("Are you sure you want to quit? "
+ "Yes or No");
String quit = kb.next();
if (quit.equalsIgnoreCase("y") ||
quit.equalsIgnoreCase("yes")){
System.exit(0);
}
else
{
prompt();
System.out.print("Enter a command --> ");
ans=kb.next();
}
cr.save();
System.out.println("Thank you for using this program");
}
}
}
public static void prompt(){
System.out.println("Enter one of the following commands: ");
System.out.println("a or add to add a student in the class roll");
System.out.println("sa or average to sort the students based "
+ "on their average");
System.out.println("sn or names to sort the students "
+ "based on their last names");
System.out.println("r or remove to remove a student from the class roll");
System.out.println("s or save to save the list of students back to the input"
+ "datafile");
System.out.println("d or display to display the class roll");
System.out.println("c1 or change1 to change score 1 of a student");
System.out.println("c2 or change2 to change score 2 of a student");
System.out.println("c3 or change3 to change score 3 of a student");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");}
Class Roll
public class ClassRoll {
ArrayList students = new ArrayList();
private String title;
private String fileName;
public ClassRoll(String f) throws IOException{
//acquires title of file
Scanner fileScan;
Scanner lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Course Title: " + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student name = new Student(firstName, lastName);
name.setScore1(lineScan.nextInt());
name.setScore2(lineScan.nextInt());
name.setScore3(lineScan.nextInt());
students.add(name);
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
}
}
void display(){
double classAverage = 0.0;
DecimalFormat f = new DecimalFormat("0.00");
System.out.println("\t" + title );
for (int i = 0; i < students.size(); i++){
//fix this part of the code, get average
Student name = (Student) students.get(i);
System.out.println(name.toString());
System.out.println("\n" + f.format(name.getAverage()));
classAverage = classAverage + name.getAverage();
}
System.out.println("\t\t\t" + f.format(classAverage / students.size()));
}
void add(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
System.out.print("Score 1: ");
int score1 = input.nextInt();
System.out.print("Score 2: ");
int score2 = input.nextInt();
System.out.print("Score 3: ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
static void changeScore1(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's first Exam score: ");
Integer score1 = kb.nextInt();
System.out.println("New score of Exam 1: ");
Integer newScore1 = kb.nextInt();
score1 = newScore1;
}
static void changeScore2(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's second Exam score: ");
Integer score2 = kb.nextInt();
System.out.println("New score of Exam 2: ");
Integer newScore2 = kb.nextInt();
score2 = newScore2;
}
static void changeScore3(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's third Exam score: ");
Integer score3 = kb.nextInt();
System.out.println("New score of Exam 3: ");
Integer newScore3 = kb.nextInt();
score3 = newScore3;
}
private int search(String fn, String ln) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(fn, ln)) {
return i;
} else {
i++;
}}
return -1;
}
Student find(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}
}
void remove(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student was not found within the list");
}
}
void sortAverage(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}
}
void sortNames(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}}}
void save() throws IOException{
OutputStream file = new FileOutputStream("data.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
output.close();
}}
}
Error Messages
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ClassRoll.<init>(ClassRoll.java:38)
at Assignment4.main(Assignment4.java:16)
hasNext() is a precondition for next(), or else you will get those exceptions. So hasNext() must match the corresponding next()

Scanner ignoring the String "name"

I am trying to take user input for name, last name, phone number and age.
For some odd reason the scanner is skipping name but none of the other variables.
Can someone point out my mistake please? I can't figure it out.
import java.util.Scanner;
public class Lab2{
String [][] info = new String [10][4];
public static void main(String [] args){
new Lab2();
}
public Lab2(){
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Student contact Interface");
System.out.println("Please select a number from the options below:");
while(true){
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("3: Display the contact list.");
System.out.println("0: Exit the contact list.");
int options = input.nextInt();
String name, lastName, number, age;
switch(options){
case 1:
System.out.println("Please enter the name: ");
name = input.nextLine(); // This is the String var that is not accepting input from...
System.out.println("Please enter the last name: ");
lastName = input.nextLine();
System.out.println("Please enter the phone number: ");
number = input.nextLine();
System.out.println("Please enter the age (eg. 25): ");
age = input.nextLine();
addStudent(name, lastName, number, age);
break;
case 2:
System.out.println("\nEnter the name to remove: ");
String delName = input.nextLine();
System.out.println("\nEnter the last name to remove: ");
String delLastName = input.nextLine();
remove(delName, delLastName);
break;
case 3:
display();
break;
case 0:
System.out.println("Thank you for using the contact Database.");
System.exit(0);
}
}
}
public void addStudent (String name, String lastName, String number, String age){
boolean infoInserted = false;
for(int i = 0; i < 10; i++){
if(info[i][0] == null || info[i][0].equals(null)){
info[i][0] = name;
info[i][1] = lastName;
info[i][2] = number;
info[i][3] = age;
infoInserted = true;
break;
}
}
if(infoInserted){
System.out.println("\nContact saved.\n");
}
else{
System.out.println("\nYour database is full.\n");
}
}
public void remove(String delName, String delLastName){
boolean removed = false;
int i = 0;
for (i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
if (info[i][0].equals(delName) && info[i][1].equals(delLastName)) {
while (i < 9) {
info[i][0] = info[i + 1][0];
info[i][1] = info[i + 1][1];
info[i][2] = info[i + 1][2];
info[i][3] = info[i + 1][3];
i++;
}
info[9][0] = null;
info[9][1] = null;
info[9][2] = null;
info[9][3] = null;
removed = true;
break;
}
}
}
if (removed) {
System.out.println("Contact removed.");
}
else {
System.out.println("Contact was not found.");
}
}
public void display (){
for (int i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
System.out.println("Contact " + (i + 1)+ ":");
System.out.println("\t" + info[i][0]);
System.out.println("\t" + info[i][1]);
System.out.println("\tPhone Number:" + info[i][2]);
System.out.println("\tAge:" + info[i][3]);
}
}
}
}
Add a
input.nextLine();
after your
int options = input.nextInt();
This is because:
nextInt method does not read the last newline character (of your integer input)
that newline is consumed in the next call to nextLine
causing name 'to be skipped'
so you need to 'flush away' the newline character after getting the integer input
Another option:
Take in the entire line, using input.nextLine()
Get the integer value using Integer.parseInt() to extract the integer value
It is skipping name because , input.nextInt() wont go to next input line.
You can use
int option=Integer.parseInt(input.nextLine());
then it wont skip name.

how to recognise capital letters and not just lower case

Hi i have done this program it works fine except if the user tries to write in capital letters i tried .toUpperCase but it still closes the program if you try to use capital letter to search can anyone help please thank you
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//my arrays
static String country [] = new String[1000];
static String capital [] = new String[1000];
static double population [] = new double[1000];
static List<String> countriesList = Arrays.asList (country); //a new array for user to add data to
public static void main (String args [])throws IOException
{
// now i am adding data to the arrays
country[0] = "Barbados";
capital[0] = "Bridgetown";
population[0] = 65.3;
country[1] = "france";
capital[1] = "paris";
population[1] = 315.8;
country[2] = "nigeria";
capital[2] = "abuja";
population[2] = 170.1;
country[3] = "USA";
capital[3] = "washington";
population[3] = 2840;
country[4] = "japan";
capital[4] = "tokoyo";
population[4] = 126.7;
int option = 0;
System.out.println("WELCOME TO MY COUNTRY DATABASE\n");
while(option!= 5){ //Only five options
options();
option = Integer.parseInt(br.readLine());
if(option > 5 || option < 1)
{
System.out.println("Wrong input! Try Again");
System.out.println("CHOOSE FROM 1 - 5 \n ");
}
if(option == 1) {
addCountry();
}
else if(option == 2){
searchCountry(); //Search from an array
}
else if(option == 3){
ListCountry();
}
else if(option == 4){
getFare(); //show fare to travel
}
else if(option == 5) {
System.out.print("\n Thank you and Goodbye ");
}
}
}
public static void options()
{
System.out.println("Main menu");
System.out.println("=========");
System.out.println("1. Add a new country");
System.out.println("2. Search for a country");
System.out.println("3. Show list of countries available");
System.out.println("4. Get fare from London to countries listed");
System.out.println("5. Exit");
System.out.print("\n Choose an option from 1 - 5: ");
}
public static void addCountry()throws IOException
{
System.out.println("\n Adding a country");
System.out.println("===================");
System.out.print("Enter name of country: ");
String countryInput = br.readLine();
System.out.print("Enter Capital: ");
String capitalInput = br.readLine();
System.out.print("Enter population: ");
String populationInput = br.readLine();
int spareSlot = -1;
for (int i = 0; i < country.length; i++) // loop so data can be added to arraylist
{
if(country[i] == null)
{
spareSlot = i;
break;
}
}
country[spareSlot] = countryInput;
capital[spareSlot] = capitalInput;
population[spareSlot] = Double.parseDouble(populationInput);
System.out.println("\n You added the country " + countryInput + ", the capital is " + capitalInput + ", with a population of " + populationInput + "\n" );
//System.out.println("================================================================================================================");
}
public static void searchCountry() throws IOException
{
Scanner in = new Scanner (System.in);//Scanner to obtain input from command window
String output;
int size, i;
System.out.println("\n Searching countries");
System.out.println("========================= \n");
System.out.print("Search a Country: ");
output = br.readLine();
boolean found = false;
//A loop to search from the array
for(i = 0; i < country.length; i++)
if(output.equals(country[i]))
{
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i +"\n");
else
System.out.println(output + ": This country is not found, choose option 1 to Add country \n");
if (output == country[0])
{
System.out.println("The capital of "+ output + "is " + capital[1] + " with a population of " + population[3]);
}
if(output == country[1]) {
System.out.println("The capital is" + capital[4]);
}
if(output == country[2]) {
System.out.println("The capital is" + capital[1]);
}
if(output == country[3]) {
System.out.println("The capital is " + capital[2]);
}
if(output == country[4]) {
System.out.println("The capital is " + capital[3]);
}
}
public static void ListCountry()throws IOException
{
for (String c : countriesList)
{
if(c!=null)
System.out.println("\n" + c +"\n"); // to list all countries so far in the array
}
}
public static void getFare()
{
Scanner input = new Scanner (System.in);
String destination;
int fare;
System.out.println("\n Get a fare:");
System.out.println("============== \n");
System.out.print("Select destination by entering number from 1 -5: \n");
System.out.println("1 Caribbean");
System.out.println("2 Europe");
System.out.println("3 Africa");
System.out.println("4 America");
System.out.println("5 Japan");
destination = input.nextLine(); //get destination from user
fare = Integer.parseInt(destination);
switch(fare)
{
case 1: System.out.println("To travel to the Carribbean the fare is from £600 \n");
break;
case 2: System.out.println("To travel to Europe the fare is from £199 \n");
break;
case 3: System.out.println("To travel to Africa the fareis from £500 \n");
break;
case 4: System.out.println("To travel to America the fare is from £290 \n");
break;
case 5: System.out.println("To travel to Japan the fare is from £550 \n");
break;
default: System.out.println("INVALID ACTION START AGAIN \n");
System.out.println("======================================");
}
}
}
You have one comparison reading
if(output.equals(country[i]))
If you want this to be case-insensitive, you want to change that to
if(output.equalsIgnoreCase(country[i]))
Later in your code, you have lines similar to
if (output == country[0])
which compares object identity rather than string equality. You want to change all these to at least properly compare strings, and possibly to be case-insensitive as above.

Categories

Resources