I am a bit new to arrays and I'm wondering how I can ask a user to input which movie they want to remove from the list of available movies and then how to return a new list that bumps each other movie up one spot. I've watched a bunch of videos but I can't figure it out.. :( It will ask me to enter my username, then show me the menu options. But once I press 3, it does not ask me which movie I would like to delete and it does not remove a movie from the array
package practice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
List<String> allowedUsernames = Arrays.asList("John", "Sam", "Lucy", "Arthur", "Trisha");
System.out.println("Welcome to the Java movie rental store! To start, please enter your username!");
String name = "";
do {
if (!name.equals("")) {
System.out.println("Please enter a valid username.");
}
name = input.nextLine();
} while (!allowedUsernames.contains(name));
System.out.println("Hello " +name+ "! Please select from the following menu options!");
getchoices();
}
public static void getchoices() {
Scanner scan = new Scanner(System.in);
String[] optionslist = {
"1) See full list of movies",
"2) Add a movie",
"3) Delete a movie",
"4) Modify a movie",
"5) Exit"
};
for (int i = 0; i < optionslist.length; i++) {
System.out.println(optionslist[i]);
}
int number = scan.nextInt();
System.out.println("You selected: " + optionslist[number-1].substring(3, optionslist[number - 1].length()));
movieList();
}
public static void printNewMovielist() {
// TODO Auto-generated method stub
String[] newList = {
"Shrek",
"Beauty and the Beast",
"Wall-E",
"Cinderella",
"Alice in Wonderland"
};
System.out.println("Movies Available: ");
newMovieList(newList);
newList = deleteMovies(newList);
System.out.println("The updates list of movies available at the rental store: ");
newMovieList(newList);
deleteMovies(newList);
}
public static void movieList() {
ArrayList<String> Movies = new ArrayList<String>();
System.out.println("Movies Available:");
Movies.add("Shrek");
Movies.add("Beauty and the Beast");
Movies.add("Wall-E");
Movies.add("Cinderella");
Movies.add("Alice in Wonderland");
for (int i = 0; i <Movies.size(); i++) {
System.out.println(Movies.get(i));
}
}
public static String[] deleteMovies (String [] newList) {
String[] deleteMovie = new String [newList.length - 1];
for (int i = 0; i < newList.length; i++) {
deleteMovie[i] = newList[i];
}
Scanner sc = new Scanner (System.in);
System.out.println("Which movie would you like to delete?");
return deleteMovie;
}
public static void newMovieList(String [] newList) {
for (int i = 0; i < newList.length; i++) {
System.out.println((i - 1) + " )" + newList[i]);
}
}
public static String[] deleteMovies(String[] newList) {
String[] deleteMovie = new String[newList.length - 1];
for (int i = 0; i < newList.length; i++) {
deleteMovie[i] = newList[i];
}
Scanner sc = new Scanner(System.in);
System.out.println("Which movie would you like to delete?");
return deleteMovie;
}
You can see above that sc is not used. You create the scanner but you don't ask the user for a nextLine()! Contrast this with how you did it with the input scanner. Therefore, your program will exit because it finished (it's not waiting for a nextLine() from the user).
Edit: As K450 pointed out in the comments, you don't even reach this above point in the code. You simply print out which option they select, and then list all movies, and that's all. If your program sees that the user tries to delete a movie (entered that option), you should call this method.
To "remove" an element from an array by shifting everything, you can create an array of length n - 1 similar to what you did, but then note that the index of all elements after the removed element in the original array will be one greater than where it should be copied in the new array.
For example, if you'd like to delete Sam in the array:
["John", "Sam", "Mary"]
Then you would want `
newArray[0] = oldArray[0];
newArray[1] = oldArray[2];
There are ways to do this without using a for loop, but I would suggest at least attempting it as an exercise. A better option would probably be an ArrayList for your use case though, since you can easily remove an element at an index.
Related
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.
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm having difficulties with my homework. I have the basic logic down but I'm messing up. The objective is to make a receipt from a shopping list that's inputted by the user. For example, the user enters:
Apples
OraNgeS // also it's not case sensitive
Oranges
Bananas
!checkout //this is to indicate the list is over
Output:
Apples x1
Oranges x2
Bananas x1
I'm stuck. My code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Enter the items you wish to buy:");
String[] input = new String [keyboard.nextLine()];
keyboard.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = keyboard.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
I know I'll have to add the if statement eventually so if they type in "!checkout" it'll end the list. but I can't get past this yet.
Any tips or advice?
Try to use ArrayList <-- Link.
Array is need to statically initialize it first before you can use it while ArrayList is automatically expanding when you add values on it. you can use ArrayList without initializing a range on it. Here is the sample:
List<String> fruitList = new ArrayList<>();
Scanner keyboard = null;
Boolean isNotDone = true;
System.out.println("Press 'Q' if you want to print out.");
while(isNotDone) {
keyboard = new Scanner(System.in);
System.out.print("Input Fruits: ");
String temp = keyboard.nextLine();
if(temp.equalsIgnoreCase("q")) {
isNotDone = false;
} else {
fruitList.add(temp);
}
}
System.out.println(fruitList);
The following code will do exactly what you are looking for:
Scanner keyboard = new Scanner(System.in);
List<String> inputItems = new ArrayList<String>();
List<String> printedResults = new ArrayList<String>();
String input = keyboard.nextLine();
while(!"!checkout".equals(input))
{
inputItems.add(input);
input = keyboard.nextLine();
}
for(int i=0; i<inputItems.size();i++)
{
Integer thisItemCount = 0;
String currentItem = inputItems.get(i);
for(int j=0; j<inputItems.size();j++)
{
if(inputItems.get(j).toLowerCase().equals(currentItem.toLowerCase()))
thisItemCount++;
}
if(!printedResults.contains(currentItem.toLowerCase()))
{
System.out.println(currentItem.toLowerCase() + " x" + thisItemCount);
printedResults.add(currentItem.toLowerCase());
}
}
I am trying to pass an array from one method to another method and then copy the contents of that array into a new array. I am having trouble with the syntax to accomplish that task.
Does anyone have some reference material that I could read about this topic or maybe a helpful tip that I could apply?
I apologize if this is a noob question, but I have only been messing with Java for 3-4 weeks part time.
I know that Java uses pass by value, but what where I'm getting lost is...should I invoke the sourceArray before copying it to the targetArray?
My goal here is not to be just handed an answer, I need to understand WHY.
Thanks...in advance.
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the total number of dealers: ");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.printf("%nPlease enter the required data for each of your dealers:");
dataCalculation(numDealers);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: ");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
int[] dealerSales = new int[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
int sales = input.nextInt();
dealerSales[i] = sales;
}
for(int i = 0; i < data; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
}
//gather the required input data.
//Perform the appropriate data validation here.
}//data calculations
//METHOD 3
public static int commission(int data)
{
//Create array
int[] commissionRate = new int[dealerSales];
//Copy dealerSales array into commissionRate
System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);
//calculate the commission array.
//$1 - $5,000...8%
//$5,001 to $15,000...15%
//$15,001...20%
//
}//commission method
}//class
If you want to copy an array, you can use the Arrays.copyOf(origin, length) method. It takes 2 arguments, first one is the array from which the data is supposed to be copied and second is the length of the new array, and import java.util.Arrays.
-See the link for more info https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)
I have an array of 8 strings
(Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi")
all referenced by "county"
I'd prompt the user to input a number of 1-8 (iVal), 1 being Carter, 2 being Cocke, etc...
Is there a way I could do this other than using a switch statement?
Also, how would I go about this if the user were to input Washington I'd display "Washington is in the array" and the opposite if the string isn't in the array?
Thanks in advance.
Here is my array.
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
for (int i = 0; i< county.length; i++)
{
System.out.print (county [i]+ "\n");
}
To prompt the user to enter a county, and then display it (without a switch) is simple enough. You could use something like,
String[] county = { "Carter", "Cocke", "Washington", "Greene",
"Hawkins", "Johnson", "Sullivan", "Unicoi" };
Scanner scan = new Scanner(System.in);
for (int i = 0; i < county.length; i++) {
System.out.printf("%d %s%n", i + 1, county[i]);
}
System.out.println("Please select a county from above: ");
int choice = scan.nextInt();
if (choice > 0 && choice <= county.length) {
System.out.println("You selected: " + county[choice - 1]);
} else {
System.out.println("Not a valid choice: " + choice);
}
As for testing if a String array contains a particular String you could write a utility function using the for-each loop like
public static boolean contains(String[] arr, String val) {
if (arr != null) {
for (String str : arr) {
if (str.equals(val)) {
return true;
}
}
}
return false;
}
i was working on the same thing, use ArrayList. this was my code
import java.util.*;
public class Practice{
public static void main(String[] args){
ArrayList<String> mylist = new ArrayList<>();
mylist.add("Maisam Bokhari");
mylist.add("Fawwad Ahmed");
mylist.add("Ali Asim");
mylist.add("Maheen Hanif");
mylist.add("Rimsha Imtiaz");
mylist.add("Mugheer Mughal");
mylist.add("Maaz Hussain");
mylist.add("Asad Shahzada");
mylist.add("Junaid Khan");
System.out.println("Name of the student: "+mylist);
}
}
now if u want a specific name from the list put this in system.out.println
System.out.println("Name of the student: "+mylist.get(1));
now the trick is to let the user enter the number in get( )
for this i made this program, here is the code
first make a scanner
Scanner myScan = new Scanner(System.in);
int a = myScan.nextInt();
System.out.println("Name of the student: "+mylist.get(a));
now it will only print that name depending on what number user have entered !!
I didn't understand well your questions, but I am going to answer on what I have understand.
In case you want to print the value of a given index by the user here is the solution:
Try an i with correct (existing) index and another one which does not exist e.g i=9
public class app
{
public static void main(String[] args)
{
String [] county ={"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
int i = 10; //i is the user input, you should do that using a BufferedReader or Scanner.
try
{
System.out.println(county[i-1]);
}
catch(IndexOutOfBoundsException e)
{
System.out.println("This index doesn't exist");
}
}
}
In case you want to check if a given word exist you can do it that way:
Again try a string which exist and one which does not exist.
public class app
{
public static void main(String[] args)
{
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
String word = "Cocke"; //word is the user input, you should do that using a BufferedReader or Scanner.
boolean found = false;
for(int i=0; i<=7; ++i)
{
if(word == county[i])
{
found = true;
break;
}
}
if(found == true)
{
System.out.println(word + " is in the array.");
}
else
{
System.out.println(word + " is not in the array.");
}
}
}
int number = keyboard.nextInt();
String [][] myArray = new String[number][1]
for (int i = 0; i < x; i++)
{
System.out.println("Enter food name: ");
myArray[i][0] = keyboard.nextLine();
for (int j = 0; j < 1; j++)
{
System.out.println("Enter the type of this food: ");
myArray[i][j] = keyboard.nextLine();
}
}
Here is my code for what I am about to ask. I want it to print out these outputs when I run this program:
Enter food name:
(where user type his or her input)
Enter the type of this food:
(where user type his or her input)
(My problem is it prints out this instead for the first loop:)
Enter food name:
Enter the type of this food:
(where user type his or her input)
With no way of entering the food item. After the first loop, then the program is back to normal with the output I want, but how do I change the code so that the first loop will take in user input for "enter food name: "?
Thanks in advance.
Edit: sorry for not seeing that question beforehand but that one is not about a for loop so if I enter an empty string before the next input, my loop will not work. Is there any fix to this?
Edit: Got it to work. Thanks everyone.
You might try something like the code below (this allows information to be entered until the user types end .. rather than requiring the user to know how many items they will enter. Also, a method is created to handle the input .. so you can improve, adjust the method easily.
import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.Scanner;
public class Foodarray {
private static String[][] foodInformation;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
foodInformation = getFoodInformation(keyboard);
}
private static String[][] getFoodInformation(Scanner inputDevice) {
String[][] result = null;
boolean isStoping = false;
ArrayList<String> holdName = new ArrayList<String>();
ArrayList<String> holdType = new ArrayList<String>();
while (!isStoping) {
System.out.println("Enter food name (or end to exit): ");
String foodName = inputDevice.nextLine().trim();
isStoping = "end".equalsIgnoreCase(foodName);
if (!isStoping) {
System.out.println("Enter food type");
String foodType = inputDevice.nextLine().trim();
holdName.add(foodName);
holdType.add(foodType);
}
}
int foodCount = holdName.size();
if (foodCount>0) {
result = new String[foodCount][foodCount];
for (int i=0; i < foodCount; i++) {
result[i][0] = holdName.get(i);
result[i][1] = holdType.get(i);
}
}
return result;
}
}