Getting multiple Strings into an Array [duplicate] - java

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());
}
}

Related

Removing a specific element from array through user input

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.

Java Array List - finding duplicate in While loop

I tried solving this ArrayList problem but no luck
Anyway in while loop I have to add new String items to the ArrayList.
If there is a duplicate item there should be a message that says REPEATED ITEM.
While loop will break by word END
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
lista1.add(in.nextLine());
if(lista1.containsAll(lista1)){
System.out.println("Repeated words");
}
if(lista1.contains("end")) {
break;
}
}
for(String data:lista1)
System.out.println(data);
}
If I understand what you're trying to do correctly, I believe it appears that you're trying to loop over user input until they type "end", each input to a list, and state if you already added that word by printing out "repeated word". If that's the case, you're pretty close. You just need to understand how to use the list data structure a little bit better.
public static void main(String[] args) {
ArrayList<String> lista1 = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("enter words: ");
String userInput = in.nextLine();
if (lista1.contains(userInput)) { // checks if user's input is already in lista1
System.out.println("Repeated word: " + userInput);
} else { // if it's not, then add user's input to lista1
lista1.add(userInput);
}
if (lista1.contains("end")) { // if lista1 contains "end", exit loop
break;
}
}
for(String data:lista1)
System.out.println(data);
}

Adding .split into my code

I'm creating a console program in Java with an array, I need to enter all of my code on one line in the following format up to 100 times.
car_make_name : car_model_name : car_model_tax : car_model_price
It's two strings and two int variables, I have code written out but I don't know how to use .split to enter the correct information into the corresponding variable.
This is my code:
public class Main {
public static void main (String[] args)
{
//Arrays declared
String[] cars = new String[20];
String[] car_model_name = new String[20];
int[] car_model_tax = new int[20];
String[] car_make_name = new String[20];
int[] car_model_price = new int[20];
Scanner scan = new Scanner (System.in);
//Loop??
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("quit", "QUIT", "Quit")) {
}
}
break;
for (int x = 0; x < cars.length; x++){
System.out.println("Enter details, separating each with a ':' ");
cars[x] = System.console().readLine();
}
}
}
First, you may prefer List but not array to store your information if you read input from console and you can't control the input length of your user.
Second, you may want to use String#split to split and convert it if necessary.
System.out.println("Enter details, separating each with a ':' ");
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("quit")) {
break;
}
final String[] split = line.split(":");
// handle it
}
Third, A good book can improve your programming level so much.If you have no experience of programming, I recommend Head First Java. Otherwise, I recommend Thinking In Java.

Arrays in Java, getting 'array required, but arrayList<string> found' [duplicate]

This question already has answers here:
Get specific ArrayList item
(8 answers)
Closed 7 years ago.
The code is trying to take String entries, add them to an array and then stop when no text is written (user just presses enter). Then it is meant to display all of the String items in the array thus far on new lines.
The error in my title is coming up on my if query, and I'm additionally getting error's reading the value 'x' in the for loop as a variable (cannot find symbol).
Can anyone help me out
import java.util.Scanner;
import java.util.ArrayList;
public class FirstPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty[i].isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
}
}
The error message is telling you exactly what is wrong. You've got an ArrayList and are trying to treat it as if it were an array. It isn't, and you can't use array indices, [i] on it. Instead use the get(...) method as any tutorial will tell you (and which I strongly recommend that you read -- Google can help you find one).
Your tillEmpty is not an array but an arraylist...you have to use tillEmpty.get(i).isEmpty instead of tillEmpty[i]
You missed int in your for loop:
for (int x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
You are accessing list as Array, use below code, this should work:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty.isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (int x = 0; x < tillEmpty.size(); x++){
System.out.println(tillEmpty.get(x));
}
}

Why is my Java while loop making two passes first? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Why is my while loop making two passes before allowing user input? Tried the same with for loop and can't figure out why it's asks for input twice before allowing user to enter input. I know it's a stupid, simple logic mistake I'm making but I'm a noob. Thanks in advance.
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
}
}
Output looks like
How large would you like the array to be? (number)
5
Please type a string to be entered in the array
Please type a string to be entered in the array
Add scan.nextLine(); right after your nextInt:
int arraySize = scan.nextInt();
scan.nextLine();
The first iteration of the while loop is not blocking on the nextLine() because it is picking the new line after the first integer that you input.
Try this:
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("How large would you like the array to be? (number)");
int arraySize = scan.nextInt();
scan.nextLine(); // This advances the Scanner to the next line.
String [] myArray = new String [arraySize];
int i = 0;
if (arraySize <= 0 ) {
System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
} else {
while (i < myArray.length) {
System.out.println("Please type a string to be entered in the array");
myArray[i] = scan.nextLine();
i++;
}
}
}

Categories

Resources