Using Objects in Method - java

I am trying to use a menu system that can delete a customer from my array myHotel[], this is built from an object.
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
...
public void deleteCustomer(String myHotel[]){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
roomNum=input.nextInt();
myHotel[roomNum].setName("e");
}
I get the errors, cannot find symbol?
Here is the Full Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int roomNum=0;
Room[] myHotel = new Room[10];
for (int x =0; x<10; x++){
myHotel[x] = new Room();
}
String roomName;
String menu;
do {
System.out.println("Please Select an Option from the Menu:");
System.out.println("Enter V to View all Rooms");
System.out.println("Enter A to Add Customer to Room");
System.out.println("Enter D to Delete Customer from Room");
System.out.println("Enter Q to Quit");
menu=input.next();
//if(menu.charAt(0) == 'V')viewAllRooms();
//if(menu.charAt(0) == 'A')addCustomer();
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
} while (menu.charAt(0) != 'Q');
while (roomNum < 10) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
for (int x = 0; x < 10; x++) {
//System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
}
public void deleteCustomer(String myHotelRef){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
int deleteRoom=input.nextInt();
myHotelRef[deleteRoom].setName("e");
}
}

You get multiple errors. What is myHotel[]? roomNum is not defined, etc.
Please use your compiler.
Also: please read https://stackoverflow.com/help/how-to-ask :-)

First you need declare myHotel array and pass it with out [].
deleteCustomer(myHotel);
Second, there is not such a method setName(String name) in String class
myHotel[roomNum].setName("e");// no such a method
Third, you need to declare the roomNum variable like:
int roomNum = input.nextInt();

Your main problem is that you've included [] in your call to deleteCustomer. It should be:
if (menu.charAt(0) == 'D') {
deleteCustomer(myHotel);
}
When you reference an array object as a whole you don't include square brackets. Square brackets are for the declaration, initialisation and for accessing individual elements within the array.
I'd also recommend that you get into the habit of always using curly braces with your if, for and while constructs, as not including them is often the cause of bugs. It also makes it easier to read when you come back to it, and you're clearly indicating to others what should be part of the loop and what shouldn't.

Related

Java program crashing when attempting to show a menu and retrieve input from user (NoSuchElementException)

So I have a program that takes orders for vehicle purchases (meant to learn the basics of java. Right now this iteration of the assignment is focusing on inheritance). Hierarchy: Orders.java (Main program), Vehicle.java (parent class), Boat.java/Car.java/Truck.java(child classes).
I was showing my menus manually in the main program before but tried to delegate that responsibility to my Vehicle class so it would be more generic and each child could pass in a Question Prompt and Array of Choices to the showMenu function. So nothing was being done manually anymore.
Here's what happened when it was done manually (worked fine):
System.out.println("What type of Car is this?");
System.out.println("\t1. Sedan");
System.out.println("\t2. Coupe");
System.out.println("\t3. Wagon");
System.out.print("Choice: ");
while (!sc.hasNext("[123]")) {
System.out.println("");
System.out.println("");
System.out.println("That's not an option! Please try again.");
System.out.println("What type of Car is this?");
System.out.println("\t1. Sedan");
System.out.println("\t2. Coupe");
System.out.println("\t3. Wagon");
System.out.print("Choice: ");
sc.next();
}
choice = sc.next();
if(choice.equals("1")){
car.setCarType("Sedan");
} else if (choice.equals("2")){
car.setCarType("Coupe");
} else if (choice.equals("3")){
car.setCarType("Wagon");
} else{
car.setCarType("unknown");
}
Here's how it works now (crashes before stopping to let the user give input):
public int showMenu(String prompt, String[] choices){
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
String choiceIdentifiers = "";
int choice;
for(int i = 0; i < choices.length; i++){
Integer j = i+1;
System.out.println("\t\t" + j + ". " + choices[i]);
choiceIdentifiers = choiceIdentifiers + j.toString();
}
System.out.print("Choice: ");
while (!sc.hasNext("[" + choiceIdentifiers +"]")) {
System.out.println("");
System.out.println("");
System.out.println("That's not an option! Please try again.");
System.out.println(prompt);
for(int i = 0; i < choices.length; i++){
System.out.println("\t\t" + (i+1) + ". " + choices[i]);
}
System.out.print("Choice: ");
sc.next();
}
choice = Integer.parseInt(sc.next());
sc.close();
return choice - 1;
}
Also here's a link to my github repo with the full program.
What could be happening in the showMenu function to crash the program and throw the NoSuchElementException?
Any help would be greatly appreciated.
The problem is that you're closing the System.in stream when you call sc.close().
When you construct a new Scanner that uses the closed System.in stream and you call next() on it, you'll get this error.
To solve the problem, don't close the System.in (don't call close() on any Scanner that uses this stream) until you're done processing user input.
Here is a MCVE:
public class Example {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
sc1.close();
Scanner sc2 = new Scanner(System.in);
sc2.next();
}
}
The problem is in Vechile.java show menu method
Scanner sc = new Scanner(System.in);
System.out.println(prompt);
String choiceIdentifiers = "";
int choice;
for(int i = 0; i < choices.length; i++){
Integer j = i+1;
System.out.println("\t\t" + j + ". " + choices[i]);
choiceIdentifiers = choiceIdentifiers + j.toString();
}
so here after iterating on choices array you are concatinating choiceIdentifiers string that will become 12 after loop but you are expecting input from user as 1 or 2 for model type of vechile so if you will put 1 for model then
!sc.hasNext("[" + choiceIdentifiers +"]")
is not having 1 so it will throw no such element error , hope this will help you

How do I set the conditional statement in this program?

So this code asks for a name and a number 1-20, but if you put in a number over 20 or below 1 the program still runs and I know I need a conditional statement right around figuring out the amount for "ano" to stop and re-ask the statement and re-run the segment but I don't know how to implement it into the code.
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}
Replace your while loop with this:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}
Try to surround your ano = userno.nextInt() in a while loop. (i.e., while(ano < 1 || ano > 20)) and put a prompt inside that while loop. That way, it will keep reading a new number until it finally no longer fulfills the while loop and will break out.

Searching String trouble in single array for java

I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.

Print a value from 2d array in Java

I am working on a program that allows a user to add values to a 2d array and then search the array and display the value. The information is being stored properly, but all I can get to display is the animal name and not the food. Before I get grilled I've searched and implemented a bunch of different methods trying to get the correct output. I'm sure my error is pretty simple if someone could just help me understand, thanks!
/*This program will allow a user to enter information into the zoo
or search by animal for the type of food it eats*/
import java.util.Scanner;
class zoo {
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
//prompt the user to search or quit
System.out.println("Please enter the name of the animal to search for or Q to quit: ");
String animalName = in.nextLine();
animalName = animalName.toUpperCase();
if(animalName.equals("Q")){
System.out.println("Thanks for using the program!");
}
else {
searchArray(animalName);
}
return animalFood;
}
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
arrayItem = animalFood[i][j];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
}
else {
//nothing found
}
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
//constructor
public zoo() {
}
//overloaded constructor
public zoo(int x) {
int number = x;
animalFood = addArray(x);
}
//method to get users choice
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
System.out.println("Please make a choice in the menu below");
System.out.println("-------------------------\n");
System.out.println("1 - Add animals and the food they eat.");
System.out.println("2 - Search for an animal in the zoo.");
System.out.println("3 - Exit the program");
selection = input.nextInt();
return selection;
}
//main method
public static void main(String[] args) {
//create a new object
zoo myZoo = new zoo();
//variables and scanner
int userChoice;
int numberAnimals;
String animalName = "";
Scanner input = new Scanner(System.in);
//call the menu
userChoice = menu();
//actions based on user choice
if (userChoice == 1) {
System.out.println("How many animals would you like to enter information for?");
numberAnimals = input.nextInt();
myZoo.addArray(numberAnimals);
}
if (userChoice == 2) {
System.out.println("Please enter the name of the animal to search for: ");
animalName = input.nextLine();
myZoo.searchArray(animalName);
}
if (userChoice == 3) {
System.out.println("Thank you for using the program!");
}
}
}
It looks to me like your problem is in searchArray. Your nested for loops are iterating over the size of only one dimension of the array:
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
...
}
}
Replace animalFood.length with animalFood[i].length, like you did correctly in the addArray method.
EDIT
It also looks like your output method is incorrect.
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
In this line, animalFood[j] should be animalFood[i][j]. The strange output you're seeing is Java's attempt at converting an array into a String.
2nd Edit
After examining the addArray method, it seems I've made an incorrect assumption about your array. It appears your array is structured such that each index has 2 items, the animal, and its food. So it looks like so:
animalFood[0][0] = 'Cat'
animalFood[0][1] = 'Cat food'
animalFood[1][0] = 'Dog'
animalFood[1][1] = 'Dog food'
etc.
If this is the case, then you're going to want to change your loop to only iterate over the outer index. This means removing the inner for loop inside of searchArray. Then, you're only going to compare the first index of the inner array to the item you want to match, and if there's a match, then the food will be the second index. I'll leave implementation up to you (since this looks like a homework question). If something I've said here sounds wrong, let me know.

reading input with Scanner; output is printed twice [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I have following class
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = sc.nextInt();
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
I can't type song name nr 1 because it Always shows first two together.
Like this if I type 3:
How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2:
Change
int songs = sc.nextInt();
to:
int songs = Integer.parseInt(sc.nextLine().trim());
and it will work fine.
You should not mix usages of nextInt with nextLine.
add sc.nextLine(); after int songs = sc.nextInt();
Once you enter a number and read it using a scanner ( as a number) using sc.nextInt();, the newline character will be present in the input stream which will be read when you do sc.nextLine(). So,to skip(over) it, you need call sc.nextLine() after sc.nextInt();
Add a sc.nextLine() after sc.nextInt() and your code works fine.
The reason is the end of line after you type the nomber of songs.
Either use nextInt or nextLine, I would opt for nextLine:
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
put a sc.nextLine(); after int songs = sc.nextInt();

Categories

Resources