import java.util.Scanner;
public class EmpTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// there is a second class with my constructors and other stuff of that nature
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
String no = "no";
String yes = "yes";
while (true) {
System.out.println("Please enter in the employee name");
e1.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e1.salary = input.nextDouble();
while (true) {
System.out.println("Would you like to add a second employee?");
String userInput = input.next();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e2.name = input.next();
System.out.println("Please enter in the salary of that employee");
e2.salary = input.nextDouble();
}
//this is where my break wont terminate the loop
//the console output just asks for the second employee salary and name without waiting for a user input
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
System.out.println("Would you like to add a third employee?");
userInput = input.next();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e3.name = input.next();
System.out.println("Please enter in the salary of that employee");
e3.salary = input.nextDouble();
}
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
}
}
}
}
your break statement is breaking inner while loop but no break statement for outer while loop.
After my first wrong answer here's the correct thing. As by the JLS:
A break statement with no label attempts to transfer control to the innermost
enclosing switch, while, do, or for statement of the immediately enclosing
method
So in your case you are breaking the inner while(true)-loop.
If you want to break some "outer" block you have to use break with a label like this:
loop:
while(true) {
.....
while(true) {
...
break loop;
}
}
Here is my answer with some explanations on the code:
import java.util.Scanner;
public class EmpTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
String no = "no";
String yes = "yes";
//initialized userInput here so that we can use it on the outer loop
String userInput="";
while (true) {
System.out.println("Please enter in the employee name");
e1.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e1.salary = input.nextDouble();
input.nextLine();
//nextDouble() reads only the double and doesn't finish the line, so we need to add nextLine() method after nextDouble()
while (true) {
System.out.println("Would you like to add a second employee?");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e2.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e2.salary = input.nextDouble();
//again
input.nextLine();
}
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
System.out.println("Would you like to add a third employee?");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase(yes)) {
System.out.println("Please enter in the employee name");
e3.name = input.nextLine();
System.out.println("Please enter in the salary of that employee");
e3.salary = input.nextDouble();
input.nextLine();
}
if(userInput.equalsIgnoreCase(no)) {
System.out.println("Okay");
break;
}
}
//do the remaining things
//add the condition for breaking the outer loop if there's any
break;
}
//never forget to close the scanner
input.close();
}
}
some notes:
nextDouble() reads only 1 double and doesn't finish the line, so I
added input.nextLine() to finish the line.
I just added a break on the outer loop, right after the inner loop.
I don't know if you have a condition for breaking the outer loop, or
if there's anything that you want to do after breaking the inner
loop
You can also convert that loop into method and just use "return"
statement to break out of the method. I don't know if it's allowed
though, so I just stick to how you created the program and modified
it a bit.
Never forget to close the scanner after using it
You have to provide 2 break statements, one for the inner while loop and another for the outer while loop.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
For example, we have 5 courses available: comp2011, comp2012, comp2013, comp2014, comp2015.
When adding or dropping a course, you need to specify the student's name (you may assume it is unique) and the course that is going to be added/dropped.
For adding a course, if the student has already enrolled in at least one course, the system will append the newly added course to his/her course record. But if it is the first time the student is trying to add courses, the system will create a record for him/her and state that this is the first course of this student (see sample output below)...
The system should support listing the courses that the student has enrolled in.
The system should support some basic validation check: Students cannot add the same course two times nor drop a course that is not enrolled.
When dropping the last course, there will be nothing in the student course list, but the system should still keep the empty file for him/her so that when another course is added, it knows that this is not the first time.
How Can I Make the Array that is going to support all my methods at once knowing that I made a method for adding, dropping, listing and quitting.(Quiting is not having an array)
This is where I am at now:
import java.util.*;
public class codeTraining {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
switch (AddDrop) {
case "A" -> A();
case "D" -> D();
case "L" -> L();
case "Q" -> Q();
default -> System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
}
public static void Q() {
System.out.println("Quit...");
}
}
You could use a hashmap for this problem, as it will allow you to quickly and easily look up the courses of students. It's declared as a global variable outside all of the methods, which means it can be accessed by any of them.
import java.util.*;
public class codeTraining {
//Hashmap contains names that are mapped to lists of courses
static HashMap<String, ArrayList<String>> map =
new HashMap<String, ArrayList<String>>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
//added breaks to the switch statement
switch (AddDrop) {
case "A": A(); break;
case "D": D(); break;
case "L": L(); break;
case "Q": Q(); break;
default: System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
//if the map contains the name already
if (map.containsKey(name)) {
//if the student already had the course in its list
if (map.get(name).contains(course)) {
System.out.println("The student is already taking this course");
return;
} else {
//adding the course to the list that's mapped
//to the student's name in the hashmap
map.get(name).add(course);
}
}
//if student isn't in the system
else {
//create a new arraylist with the new course in it
ArrayList<String> courses = new ArrayList<String>();
courses.add(course);
//add a map between the student's name and his course list
map.put(name, courses);
}
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
//checks if name in system
if (map.containsKey(name)) {
if (map.get(name).contains(course)) {
//removing if list had the course in it
map.get(name).remove(course);
} else {
System.out.println("This student isn't taking that course");
return;
}
} else {
System.out.println("This student isn't in the system");
return;
}
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
if (map.containsKey(name)) {
//printing out courses for specified student
ArrayList<String> courses = map.get(name);
for (int i = 0; i < courses.size(); i++) {
System.out.print(courses.get(i) + " ");
}
} else {
System.out.println("This student isn't in the system");
}
}
public static void Q() {
System.out.println("Quit...");
}
}
I added some comments in case you were new to hashmaps. Basically, map.put(key, value) will add a mapped pair to the list so that when you call map.get(key), it will return whatever value you put it to. I hope this helps, and feel free to ask if you're confused.
How to modify the code in else if so that whatever I input in if will be displayed in the condition 2?
import java.util.*;
public class REPORTS
{
public static void main(String[]args)
{
int Studentid,equipid,quantity,studentid,equipid1;
String Studentname,Studentcourse,Studentlevel,equipmentname,reservationdate,returndate;
STUDENT stud=new STUDENT(1234,"abc","abc","abc");
EQUIPMENT equip;
RESERVATION reserve;
Scanner in = new Scanner(System.in);
int x = choices();
if(x==1)
{
System.out.println("Enter Student ID:");
Studentid=in.nextInt();
in.nextLine();
System.out.println("Enter Student Name:");
Studentname=in.nextLine();
System.out.println("Enter Student Course:");
Studentcourse=in.nextLine();
System.out.println("Enter Student Level:");
Studentlevel=in.nextLine();
stud.setID(Studentid);
stud.setName(Studentname);
stud.setCourse(Studentcourse);
stud.setLevel(Studentlevel);
}
else if(x==2)
{
stud.display();
}
}
I'm thinking of using a looping but I dont know how to properly loop in order for me to fetch the data that is input by the user in the if statement.
I changed my if else to switch and tried a while loop. But the program runs endlessly and instead of displaying what I input it keeps asking for student name:
while(x!=7)
{
switch(x)
{
case 1:
{
stud.getData();
choices();
break;
}
case 2:
{
stud.display();
break;
}
}
}
A few starting points:
public static void main(String[]args)
{
int Studentid,equipid,quantity,studentid,equipid1;
String Studentname, Studentcourse, Studentlevel, equipmentname,
reservationdate, returndate;
STUDENT stud=new STUDENT(1234,"abc","abc","abc");
...
Rename your STUDENT class to Student. Also, you don't need all these local variables, they just make your code harder to read.
Provide a default constructor for Student
public static void main(String[]args)
{
Student stud=new Student(); // call the default constructor, don't enter bogus data
Scanner in = new Scanner(System.in);
int x = choices();
while (x != 7) {
switch(x) {
case 1:
System.out.println("Enter Student ID:");
stud.setID(in.nextInt());
in.nextLine();
System.out.println("Enter Student Name:");
stud.setName(in.nextLine());
System.out.println("Enter Student Course:");
stud.setCourse(in.nextLine());
System.out.println("Enter Student Level:");
stud.setLevel(in.nextLine());
break;
case 2: stud.display(); break;
}
// this must be inside the loop!!
x = choices();
}
}
I'm trying to write a progam that prompts the user to enter the number of students followed by prompting for username and grade. It runs once (meaning I get asked the number of students, I can enter the first name and number), and then it gives an InputMismatchException.
Can you see what's wrong?
public class LowestScore {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print ("Enter the number of students");
int numberOfStudents = input.nextInt();
int number = 0;
while (number <= numberOfStudents) {
number++;
System.out.println ("Enter student name");
String studentName = input.nextLine();
System.out.println ("Enter grade");
int grade = input.nextInt();
}
Error
run: Enter the number of students12 Enter student name Enter grade josje 8
Exception in thread "main" java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
demo.LowestScore.main(LowestScore.java:31) Java Result: 1
You need to catch the carriage return after each of the nextInt call.
Scanner input = new Scanner(System.in);
System.out.print ("Enter the number of students");
int numberOfStudents = input.nextInt();
input.nextLine(); // catch it
int number = 0;
while (number <= numberOfStudents) {
number++;
System.out.println ("Enter student name");
String studentName = input.nextLine();
System.out.println ("Enter grade");
int grade = input.nextInt();
input.nextLine(); // catch it
}
Notice that you can still run into an exception if you enter an invalid Integer.
Edit:
Basicly the nextInt catches a number that you do input, but it doesn´t catch the carriage return (the new line you are creating by pressing enter). So what it does is, you enter a number for the amount of students, lets say 1. The nextLine call instantly gets the carriage Return, creates an empty Student name and you jump straight forward to the next nextInt call. This goes on until you reach the complet amount of students. Calling nextLine after the nextInt catches the carriage return, and you are able to input the student Name.
You can specifically notice this at the point where it does print
Enter student name
Enter grade
at the same time. You allways jump directly to the next input for an Integer.
Edit2:
if you would like to catch the Exception for a wrong input aswell, then you could do it like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfStudents = -1;
boolean exception = true;
do {
try {
System.out.print("Enter the number of students");
numberOfStudents = input.nextInt();
exception = false;
} catch (InputMismatchException e) {}
input.nextLine();
} while (exception);
int number = 0;
while (number <= numberOfStudents) {
exception = true;
number++;
System.out.println("Enter student name");
String studentName = input.nextLine();
int grade;
do {
try {
System.out.println("Enter grade");
grade = input.nextInt();
exception = false;
} catch (InputMismatchException e) {}
input.nextLine();
} while (exception);
// input.nextLine();
}
}
Check out this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students");
int numberOfStudents = input.nextInt();
int number = 0;
while (number < numberOfStudents) {
String num = input.nextLine();
System.out.println("Enter student name");
String studentName = input.next();
System.out.println("Enter grade");
int grade = Integer.parseInt(input.next());
number++;
}
}
The objective is to create an account registration method for an ATM object. But I keep breaking on the if statement used to enter the loop. I assume my "wording" is off, but I'm drawing a blank on how to fix it. Any suggestions? The problem itself is at if(acc[i].getAcc()==0)where .getAcc is a getter in a class.
package atmassignment;
import java.util.Scanner;
public class AtmAssignment {
static Scanner in = new Scanner(System.in);
static int cou = 1;
static Account[] acc = new Account[10];
public static void main(String[] args) {
menu();
}
public static void menu(){
char opt;
System.out.println("Thanks for accessing ATManager.");
System.out.println("Please select a menu option to proceed.");
System.out.println("1-Register a new account, 2-Access an account, 0-Exit ATManager");
opt = in.next().charAt(0);
switch (opt) {
case '1':
newAccount();
break;
case '2':
selAccount();
break;
case '0':
System.out.println("Goodbye.");
break;
default:
System.out.println("Invalid Entry.");
break;
}
}
public static void newAccount(){
System.out.println("Account registration");
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i] = new Account(cou, bal, cus);
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
}
}
This allocates an array of object references:
static Account[] acc = new Account[10];
However it doesn't actually allocate any objects, so you are probably getting a null pointer exception when you try to access the first element. In your init code, do something like this:
for(int i = 0; i < 10; i++)
acc[i] = new Account();
You call acc[i].getAcc()==0 before actually constructing your objects. Maybe modify the for loop so that you create your objects and then gather input and update your objects later on with setter methods? This of course requires that you have some sort of default constructor for your Account class.
acc[j through maxLength] = new Account(); //where j spans the entire length of the array
for (int i = 0; i < acc.length; i++){
if(acc[i].getAcc()==0){
System.out.println("Please enter your first name...");
String fn = in.next();
System.out.println("Please enter your last name...");
String ln = in.next();
System.out.println("Please enter your address...");
String ad = in.next();
System.out.println("Please provide a contact number...");
String cn = in.next();
Customer cus = new Customer(fn, ln,ad,cn);
System.out.println("What is your starting balance...");
double bal = in.nextDouble();
acc[i].setContact(###);
acc[i].setBalance(###); //ETC
System.out.println("Your account is registered as ID#"+cou);
break;
} else {
System.out.println("Sorry, no more accounts can be created.");
break;
}
}
Probably you didn't populate your Account[] array. Here I only can see you declare your array like -
static Account[] acc = new Account[10];
So after that when you are trying to get you array element using for loop than you can't access them. You are getting the error at if(acc[i].getAcc()==0) this line. So I suggest remove the if check since you are populating your Account later in this line - acc[i] = new Account(cou, bal, cus);
Hope it will help.
Thanks a lot.
I am working on this airline program. The program should ask the user how many seats on the plane are sold and then I have this for loop to allow a user to enter a name and a meal choice for each person on the plane.
I have tried reading through some different questions about infinite for loops on stackoverflow, but I can't seem to figure out exactly what is going wrong with my code. I feel like there must be something about for loops that I am not understanding because I thought that it would only go through until your i < someNumber is no longer true.
So when I run this program, say I enter 2 seats I would expect it to go through the loop just twice, but It just keeps going. asking for a name and then a meal.
import java.util.Scanner;
public class Flyers
{
String name;
String mealType;
int economySeats;
int businessSeats;
int firstClassSeats;
int count;
public Flyers()
{
}
public String toString()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
return "Name: " + name + ", Meal " + mealType;
}
public void addEconomyFlyers()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
economySeats = in.nextInt();
for(count = 0; count < economySeats; count++)
{
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
}
}
Here is my main class if that is helpful.
import java.util.Scanner;
public class Aviation
{
public Aviation()
{
}
public static void main(String[] args)
{
int option;
FlightCost newFlight = new FlightCost();
FlightProfit flight = new FlightProfit();
Flyers newFlyers = new Flyers();
Scanner in = new Scanner(System.in);
System.out.print("Enter new flight location: ");
String location = in.next();
do{
String menu = "\n Please select an option to perform"
+ "\n1 (1) Get flight costs."
+ "\n2 (2) Get flight profits."
+ "\n3 (3) Enter names/meals."
+ "\n4 (4) Exit.";
System.out.println(menu);
option = in.nextInt();
}while (option < 0 || option > 4);
switch(option)
{
case 1:
newFlight.getCost(location);
break;
case 2:
flight.addEconomySeats();
flight.addBusinessSeats();
flight.addFirstClassSeats();
flight.getProfit(location);
break;
case 3:
newFlyers.addEconomyFlyers();
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Error: must select menu option.");
}
}
}
remove below code from toString()
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
You are already reading these from the for loop.
Also, your do-while loop is all wrong. The condition doesn't make sense. It should be option > 0 && option <4
As Pat said:
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
this code in the toString() is obsolete
however the do while does make sense, to me at least, as i see it you want the menu printed out each time the user gives an invalid int, however you are still letting 0 get through although that is not a valid choice, the do while should be:
while (option <= 0 || option > 4);
or
while (option < 1 || option > 4);
Another quirk in your code:
System.out.print("Enter a name: ");
name = in.next();
System.out.print("Enter a meal: ");
mealType = in.next();
Flyers newFlyer = new Flyers();
String seat = newFlyer.toString();
you create a new instance of the class you have just modified and call toString() on, even though you have not populated that class with data, so the toString method as it would be after the edit pat suggested will return "Name: Meal "
As i see your code is a work in progress, try adding more System.out.print on various variables for debugging purpose or use a debugger, though i know using debugger when learning can be difficult, it sure was for me. Also remember that every time you create a new instance ex:
Flyers newFlyer = new Flyers();
it has only the data that is either set by default or set in your constructor ex:
public Flyers()
{
}
I hope what i wrote was helpful, have a nice day and keep at it.