Arraylist User input - java

I would greatly appreciate some help with my java code. I am using ArrayLists to store the users favorite type of vehicles. So they will input vehicles until they type "Exit" to get out of the loop. It will then print the array list. Right now, it is only reading every other input. Depending on how many inputs there are, the user might have to type "Exit" twice before it prints the results out. Any help would be greatly appreciated, thank you!
package bacaCCh6Sec8;
import java.util.ArrayList;
import java.util.Scanner;
public class BacaCCh6Sec8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> vehicles = new ArrayList<>();
boolean done = false;
final String EXIT = "Exit";
System.out.printf("Enter your favorite vehicles.\n");
System.out.printf("Type Exit after you have input all your vehicles.\n");
do {
String input = in.next();
if (!input.equals(EXIT)) {
vehicles.add(in.next());
} else {
done = true;
} // end If
} while (!done); // End Do While
System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
} // End Main
} // End Class

the user might have to type "Exit" twice before it prints the results
out
the issue is that you're calling next() method twice hence the user must enter a value twice. the solution is to simply use the value you've got from the first next() method rather than discarding it.
String input = in.next();
if (!input.equals(EXIT)) {
vehicles.add(input); // <--- we're using the input variable
} else {
done = true;
} // end If

Each call of .next() actually reads the input. So if you call .next() twice, it'll read two lines. To rectify change vehicles.add(in.next()); to vehicles.add(input);

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> vehicles = new ArrayList<>();
boolean done = false;
final String EXIT = "Exit";
System.out.printf("Enter your favorite vehicles.\n");
System.out.printf("Type Exit after you have input all your vehicles.\n");
do {
String word = in.next();
if(word.equalsIgnoreCase("exit")) break;
vehicles.add(word);
} while (!done); // End Do While
System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
}
}
Well not my best code but it helped
Enter your favorite vehicles.
Type Exit after you have input all your vehicles.
hola
mundo
exit
Your favorite vehicles are [hola, mundo].

Related

String input of more than one word causes exception error

I am inputting the following things:
book
12.46
music cd
For some reason, the prompt for cost comes up and the next output line comes on the same line. Could someone help me to spot my mistake?
public class SalesTax {
public static void main(String[] args) {
// Input items for shopping cart
HashMap<String, String> cart = new HashMap<String, String>();
// Create a Scanner
Scanner input = new Scanner(System.in);
// variables
char done;
boolean goods;
double tax;
// Pick items for list.
do {
System.out.print("Please enter an item.");
String item = input.next();
System.out.print("Please enter the price for "+ item + ": ");
String price = input.next();
if (item.contains("book")) {
goods = false;
} else if(item.contains("chocolate")) {
goods = false;
} else if(item.contains("pill")) {
goods = false;
}
cart.put(item, price);
System.out.print("Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.");
done = input.next().charAt(0);
} while(Character.toUpperCase(done) == 'Y');
}
}
problem:
String item = input.next();
By the time you input music cd it will consume music by item and price will consume the cd thus skipping it.
solution:
you need to call input.nextLine(); to consume the whole line of string
By default, next() just gets input upto a whitespace so you'd have to use nextLine() instead, which will read in the whole line of input upto a carriage return.
use input.nextLine() to read an entire line from the keyboard. Means what ever the user typed till the user presses the enter key.
One thing that I did not understand is, what is the use of having this in your code
if(item.contains("book"))
{
goods = false;
}
else if(item.contains("chocolate"))
{
goods = false;
}
else if(item.contains("pill"))
{
goods = false;
}
???
Can you please explain?
Thanks,
you are using System.out.print() instead use System.out.println();
print() will just print the word and stays on the same line.
println() will print the whole line and cursor goes to second line .
And don't use the spaces while reading as you are writing it as
input.next();
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
edit:
just change the declaration to this.
Scanner s = new Scanner(input).useDelimiter("\n");
It will change the delimiter to new line and read the complete line.

Scanning Basics Java

So the loop works but I have to press enter twice for it to print out the next input, I know it's with my loop and I know it's because the new input is set after the method scanz but I can't put it before/ eliminate it outside the loop because then the creation of the object Scanning doesn't work. Help is appreciated!
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to terminate");
Scanner keyboard = new Scanner(System.in);
String scannedString=keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
do
{
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
scannedString=keyboard.nextLine();
}
while(!keyboard.nextLine().equals("."));
keyboard.close();
}
}
Change your loop to the following pattern:
String scannedString = keyboard.nextLine();
do {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
} while (!(scannedString = keyboard.nextLine()).equals("."));
This way condition check is done together with reading a new line. There is even more readable approach available:
String scannedString = null;
while (!(scannedString = keyboard.nextLine()).equals(".")) {
System.out.println("Numbers: "+scannedString);
scanz.set(scannedString);
scanz.printState();
}

Check for value in array

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.

Scanner looping headache

I have a homework assignment which requires input from the user and stores it in various data structures (arrays of linked-lists, stacks, etc.). However, I've been writing the main class of my previous homework assignments and this one in a very similar fashion. I have a very tiny main method. All the main method does is instantiate a new object which I don't want to be destroyed and then loop through the program forever until the user chooses otherwise. I then have a menu() method which prints a list of selections and reads the user's selection. And then from there, I pass that selection to another method which interprets the selection and performs accordingly.
The problem I have been having in the past assignments and now I've never really gotten a good answer for. The problem seems to lie with my menu() method and more specifically, the Scanner object. There always seems to be some junk left in the stream after I call the nextLine() method on a scanner object. So the next time the menu() method is called, it reads in that junk and loops though the rest of the program with that junk until menu() is called a third time. In the past, I would remedy this by calling the next() method right after I received my input and ignoring it. However, I seem to be having issues with that now as well.
In this program in particular, I have a method which request's a user enter a city name. Now, city names can be more than one word (Palm City, West Palm Beach, Satellite Beach, New York, etc.). Now, when the scanner reads in one of those multi-word cities, it does the same thing as before, reads in some junk the next time the menu() method is called and goes though the whole program with it until menu() is called again. In this case, it prints an string "Invalid Selection" and then prints the menu again. I can't for the life of me figure out what's going on. any help would be appreciated.
import java.util.Scanner;
public class CSAir
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
CityList flightLog = new CityList();
boolean loop = true;
while(loop)
{
loop = actions(menu(),flightLog);
}
}
private static String menu()
{
System.out.print("Please Make a Selection\n" +
"I) Insert a city\n" +
"A)Add a flight path (One Way)\n" +
"R) Request a flight\n" +
"L) Load from a text file\n" +
"Q) Quit\n" +
"\nSelection: ");
String in = input.next();
//input.next();
System.out.println();
return in;
}
private static boolean actions(String selection, CityList flightLog)
{
if(selection.equalsIgnoreCase("I"))
{
insert(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("A"))
{
add(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("R"))
{
request(flightLog);
return true;
}
else if(selection.equalsIgnoreCase("L"))
{
return true;
}
else if(selection.equalsIgnoreCase("Q")) return false;
else
{
System.out.println("Invalid Selection!\n");
return true;
}
}
private static void request(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
try
{
flightLog.isPath(origin, input.next());
}
catch (AllDestinationsVisitedException e)
{
e.getMessage();
}
}
private static void add(CityList flightLog)
{
System.out.print("Origin: ");
String origin = input.nextLine();
System.out.print("\nDestination: ");
flightLog.addPath(origin, input.next());
}
private static void insert(CityList flightLog)
{
System.out.print("Enter a City: ");
try
{
flightLog.addCity(input.next());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println();
}
}
Default Deliminator for scanner is white space. So when you enter New York since it has white space now scanner treats it as two tokens if you call next().
A better option would be to use nextLine() method for reading such values.

Java - Accept different keys from user to do different tasks, terminate when user clicks "X"

I'm still a newbie to Java so if this question sounds dumb, please enlighten me. Any suggestion is appreciated.
I'm thinking of some way to implement a program which allows user to input a key from the keyboard to do different tasks. The thing is, the program should be able to continue until the user clicks a specific key, let's say, "X".
This is part of the class PizzaDemo I'm working on and part of the getPizzas() method which performs the above task:
public class PizzaDemo {
private PizzaOrder list;
public PizzaDemo(){
list = new PizzaOrder();
}
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
System.out.println("To add a new Ham & Cheese pizza, press H.");
System.out.println("To add a new Pepperoni pizza, press P.");
System.out.println("To add a new Tropical pizza, press T.");
System.out.println("To exit, press X");
String input = sc.next();
while(!input.equalsIgnoreCase("H") && !input.equalsIgnoreCase("P") && !input.equalsIgnoreCase("T") && !input.equalsIgnoreCase("X")){
System.out.println("Invalid key. Enter again: ");
input = sc.next();
}
if (input.equalsIgnoreCase("H")){
System.out.println("Enter the size of the pizza: ");
String size = sc.next();
System.out.println("Enter the number of ham toppings: ");
int n1 = sc.nextInt();
System.out.println("Enter the number of cheese toppings: ");
int n2 = sc.nextInt();
Topping[] top = {createTopping("ham", n1), createTopping("cheese", n2)};
Pizza p = createHamCheese(size, top);
PizzaDemo demo = new PizzaDemo();
demo.list.setPizza(p);
getPizzas();
}
// the rest of the code is omitted
}
}
The problem is, I can't seem to find any way to use the constructor in such a way that the previously added element can still be kept even though the recursion (in the if block) is called. Anyone has some suggestion for me? The constructor is used for initializing a new pizza order, and it's a part of the program so I cannot omit it.
Thanks in advance guys.
Don't use recursion for this. You could end up with a stack overflow, no pun intended. Use a loop.
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
String input;
do{
//put code in here
} while(!input.equalsIgnoreCase("X");
}
You would have to provide an overloaded constructor that takes the List of Pizzas as an arg.

Categories