Checking for words in a loop - java

So I have this project for my computer class and I can't seem to get my program to run no matter how many different ways I try it. What I'm trying to do is have the program check if what the user types equals any of the three words (Cookies, Milk, Both) and if it doesn't ask the question again and use that input but since I'm new to java I can't seem to get it to work
Here's my code:
import javax.swing.*;
import java.util.*;
public class Cookie {
public static void main(String[] args) {
try {
Info info = new Info();
} catch(Exception e) {
System.err.println("Error! " + e.getMessage());
}
}
static class Info {
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
String word1 = "Cookies";
String word2 = "milk";
String word3 = "Both";
String flagger = "";
while (true)
if(inputs.length() !=0) {
}
for(int i=0; i<inputs.length(); i++)
{
for(int j=0; j<word1.length(); j++)
{
if(inputs.charAt(i)==word1.charAt(j))
{
flagger=flagger+word1.charAt(i)+"";
}
}
for(int j=0; j<word2.length(); j++)
{
if(inputs.charAt(i)==word2.charAt(j))
{
flagger=flagger+word2.charAt(i)+"";
}
}
for(int j=0; j<word3.length(); j++)
{
if(inputs.charAt(i)==word3.charAt(j))
{
flagger=flagger+word3.charAt(i)+"";
}
}
if(!(inputs.equalsIgnoreCase(flagger))) {
String message = String.format("%s", "Huh, I didn't get that, please say it again");
JOptionPane.showMessageDialog(null, message);
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
}
if(inputs.equalsIgnoreCase("cookies")) {
String message = String.format("%s", "Here have some Cookies :)");
JOptionPane.showMessageDialog(null, message);
}
if(inputs.equalsIgnoreCase("MILK")) {
String message = String.format("%s", "Here is the Milk you wanted :)");
JOptionPane.showMessageDialog(null, message);
}
if(inputs.equalsIgnoreCase("BOTH")) {
String message = String.format("%s", "Here is your Cookies and Milk :)");
JOptionPane.showMessageDialog(null, message);
}
}
}
}
}
}

I was able to compile your code after making few fixes. I have used a different approach, this is working, at least for most of the scenarios.
Here's my Cookie.java
public class Cookie {
public static void main(String[] args) {
try {
Info info = new Info();
info.checkInput();
} catch(Exception e) {
System.err.println("Error! " + e.getMessage());
}
}
}
And Info.java
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
public class Info {
public void checkInput() {
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
Map<String, String> words = new HashMap<String, String>();
words.put("cookies", "Here have some Cookies :)");
words.put("milk", "Here is the Milk you wanted :)");
words.put("both", "Here is your Cookies and Milk :)");
while (true) {
if (inputs != null && inputs.length() > 0) {
if (words.containsKey(inputs.toLowerCase())) {
JOptionPane.showMessageDialog(null,
words.get(inputs.toLowerCase()));
inputs = repeat();
} else {
JOptionPane.showMessageDialog(null,
"Huh, I didn't get that, please say it again");
inputs = repeat();
}
} else {
inputs = repeat(); }
}
}
private String repeat() {
return JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
}
}

You code didn't work because:
you try to use static class Info, like a method - you declare inner static method with some class fields, and then just add code like in method, this is why it will not even compile. You can change it on static or nonstatic method, or add some methods to it. For example change static class Info on static void Info(){, and call it by just Info() (insted of Info info = new Info(); in main method.
you multiple times declare String inputs = JOptionPane.showInputDialog(null,"What do you want, Cookies, Milk or Both?");, it is enough to use just inputs = JOptionPane.showInputDialog(null,"What do you want, Cookies, Milk or Both?"); second time.
you mixed some brackets, like in:
while (true)
if(inputs.length() !=0) {
} // this is problematic bracket
so it will not work at all, and all nested if statments with it.
You need to fix it to at least run your application.
EDIT
It seems that you have a lot of unnecessary code, you can shorten it for example to:
import javax.swing.*;
public class Cookie {
public static void main(String[] args) {
while (true){
String inputs = JOptionPane.showInputDialog(null,
"What do you want, Cookies, Milk or Both?");
if(inputs.equalsIgnoreCase("cookies")) {
JOptionPane.showMessageDialog(null, "Here have some Cookies :)");
break;
}else if(inputs.equalsIgnoreCase("MILK")) {
JOptionPane.showMessageDialog(null, "Here is the Milk you wanted :)");
break;
}else if(inputs.equalsIgnoreCase("BOTH")) {
JOptionPane.showMessageDialog(null, "Here is your Cookies and Milk :)");
break;
}else{
JOptionPane.showMessageDialog(null, "Huh, I didn't get that, please say it again");
}
}
}
}

It seems like you want to get input from the user, and compare it to some preset strings (cookies, milk, and both)
What if you put the whole thing into a while(true) loop, and after getting the input from the user, you wrote something like
String message;
Boolean isValid = true;
if (inputs.equalsIgnoreCase("Cookies")){
message = "Have some cookies";
}
...
else{
message = "Try again";
isValid = false;
}
JOptionPane.showMessageDialog(null, message);
if(isValid) break;
Note: I'm writing this on a mobile, so syntax may not be exact. Use your discretion.

Related

Searching for a String in an ArrayList of Objects

I have been trying to figure this out for hours and I have had no luck doing so,
I'm trying to iterate over my Arraylist<Booking> which utilizes my Booking class file and trying to understand how I'm able to search it for the matching, case-insensitive term.
this is my current method:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (int i = 0; i < bookings.size(); i++) {
while (!bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
i++;
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(), bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(), bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
}
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
I know it's messy but, just trying to make do.
I am trying to retrieve the name of the booking as I am searching by name as well as provide an error message if that names does not exist, to do that I must
use bookings.getStudent().getName() I have had some luck as I can return the value but now I am not able to provide my error message if I do not find it. Any help is appreciated.
package com.mycompany.mavenproject1;
public class Booking {
private Student student;
private int lessons;
private boolean purchaseGuitar;
// CONSTANTS
final int firstDiscountStep = 6;
final int secondDiscountStep = 10;
final int tenPercentDiscount = 10;
final int twentyPercentDiscount = 5;
final double LESSON_COST = 29.95;
final double GUITAR_COST = 199.00;
double LESSON_CHARGE = 0;
final int MINIUMUM_LESSONS = 1;
public Booking() {
}
public Booking(Student student, int lessons, boolean purchaseGuitar) {
this.student = new Student(student.getName(), student.getPhoneNumber(), student.getStudentID());
this.lessons = lessons;
this.purchaseGuitar = purchaseGuitar;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getLessons() {
return lessons;
}
public void setLessons(int lessons) {
this.lessons = lessons;
}
public boolean isPurchaseGuitar() {
return purchaseGuitar;
}
public void setPurchaseGuitar(boolean purchaseGuitar) {
this.purchaseGuitar = purchaseGuitar;
}
public double calculateCharge() {
double tempCharge;
if (lessons < firstDiscountStep) {
LESSON_CHARGE = (lessons * LESSON_COST );
} else if (lessons < secondDiscountStep) {
tempCharge = (lessons * LESSON_COST) / tenPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
} else {
tempCharge = (lessons * LESSON_COST) / twentyPercentDiscount;
LESSON_CHARGE = (lessons * LESSON_COST) - tempCharge;
}
if (isPurchaseGuitar()) {
LESSON_CHARGE += GUITAR_COST;
}
return LESSON_CHARGE;
}
#Override
public String toString() {
return student + ","+ lessons + "," + purchaseGuitar +"," + LESSON_COST;
}
}
If I understood you correctly, you are searching for a given student name in your collection of bookings. And if it is present, set a formatted text.
First of all, use a for-each loop, because you don't use the index.
Secondly, return from the for-each loop, when you found your student.
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
for (final Booking booking : bookings) // for-each
{
if (booking.getStudent().getName().equalsIgnoreCase(searchTerm))
{
String output = booking.getFormattedOutput();
this.taDisplay.setText(heading + "\n" + output + "\n");
return; // break out of the loop and method and don't display dialog message
}
}
}
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
Then there are multiple other things, which you could improve.
Don't get all the data from a booking just to format it externally. Let the Booking class handle the formatting and return you the string you desire. (move the formatting in a function inside the Booking class)
Instead of recreating a Student you receive in your Booking constructor, make the Student class immutable, and then you can just reuse the object provided.
Try also making the Booking class immutable. You provided some setters, but do you really want to change the student in a booking? Or would you rather create a new booking for the other student?
The calculteCharge method could be stateless. Just get the LESSON_CHARGE value and hold it in a local variable. Your method would also get threading-proof.
Make your constants final and better yet make them members of the class (by adding the static modifier) instead of every member.
Lastly, representing a money amount with a floating (double is better but not good either) number, you will run into funny situations. Try this calculation: 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 for example.
One way would be to create a Money class which holds the value in cents as an integer. And when you want to display the amount you can divide it by 100 and format it accordingly. That way, you can also restrict it become negative.
PS: Sometimes we desperately try to find a solution that we don't give ourselves some rest. After a little break, you might recognize the problem. Oh and try debugging with breakpoints. Or this, if you use IntelliJ IDEA (which I would highly recommend, the community edition is free).
You're re-incrementing your counter variable, which is really not going to help. Try the following:
private void searchBookings() {
if (bookings.size() <= 0) {
JOptionPane.showMessageDialog(null, "There are no bookings.", "Search Bookings", 3);
} else {
String searchTerm = JOptionPane.showInputDialog(null, "Please input search term: ", "Search Bookings", 3);
boolean studentFound = false;
for (int i = 0; i < bookings.size(); i++) {
if (bookings.get(i).getStudent().getName().equalsIgnoreCase(searchTerm)) {
String output = String.format("%-30s%-18s%-18b$%-11.2f\n", bookings.get(i).getStudent(),
bookings.get(i).getLessons(), bookings.get(i).isPurchaseGuitar(),
bookings.get(i).calculateCharge());
this.taDisplay.setText(heading + "\n" + output + "\n");
studentFound = true;
break;
}
}
}
if (!studentFound) {
JOptionPane.showMessageDialog(null, "There is no booking with that name.", "Search Bookings", 3);
}
}

How to choose an ArrayList based on user input?

I want to make the program choose from an ArrayList based on my Scanner Input.
Like, I write breakfast and than sweet, and it has to randomize the list breakfastSweet and print me the randomized index.
I am still learning Java, I am just playing around and trying to code little projects to train it.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// program begins here, you get asked what kind of lunch you want to eat
// after asking for the meal type and answering it, it goes to the next question
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
// list of meals, list name describes
ArrayList<String> breakfastSweet = new ArrayList();
ArrayList<String> breakfastSavory = new ArrayList();
ArrayList<String> lunchSweet = new ArrayList();
ArrayList<String> lunchSavory = new ArrayList();
ArrayList<String> dinnerSweet = new ArrayList();
ArrayList<String> dinnerSavory = new ArrayList();
GetRandomFromList.outputMeal(mealType, flavor, dinnerSavory); // doesn't make sense to put the list already in, I want it to automatically select the right list.
}
}
And here is the class I have already written:
import java.util.ArrayList;
import java.util.Random;
public class GetRandomFromList {
private static String randomList(ArrayList<String> list) {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
// the list should be chosen automatically, so my code doesn't work as I want it to work
public static void outputMeal(String mealType, String flavor, ArrayList<String> list){
if (mealType.equals("breakfast") && flavor.equals("sweet")){
System.out.println("What about " + GetRandomFromList.randomList() + "?");
}
}
}
Can I somehow store a list in a variable, maybe like this:
if (mealType.equals("breakfast") && flavor.equals("sweet")){
// here make a variable of the breakfastSweet list
}
I know it's hard to understand me, but English isn't my main language, hope its understandble.
To me GetRandomFromList doesn't make sense, unless GetRandomFromList contains all the data, instead, just assign a reference of the chosen List to another variable and then shuffle it to get a random value, for example...
// Previously created lists
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
ArrayList<String> userChoice = null;
if (mealType.equals("breakfast") && flavor.equals("sweet")) {
userChoice = breakfastSweet;
} else if {...}
if (userChoice != null) {
Collections.shuffle(userChoice, rand);
String value = userChoice.get(0);
}
As with most things, there are more than one way to skin this cat. For example, you could Maps to combine the type/flavors together or your could create a POJO which has information about it's type/flavor associated directly with it
POJO, with List filter...
public class Meal {
public enum Type {
BREAKFAST, LUNCH, DINNER;
public static Type forType(String value) {
try {
return Type.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public enum Flavor {
SWEET, SAVORY;
public static Flavor forFlavor(String value) {
try {
return Flavor.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
private Type type;
private Flavor flavor;
private String description;
public Meal(Type type, Flavor flavor, String description) {
this.type = type;
this.flavor = flavor;
this.description = description;
}
public Type getType() {
return type;
}
public Flavor getFlavor() {
return flavor;
}
public String getDescription() {
return description;
}
public boolean matches(Type type, Flavor flavor) {
return getType() == type && getFlavor() == flavor;
}
}
So, this defines the expected type/flavors and then allows you to define a meal of a specific type/flavor and provides a simple matches method to determine if the Meal is of a specific type/flavor, because I'm lazy.
Then we can do something like...
List<Meal> meals = new ArrayList<>(16);
// Get user input
Meal.Type type = Meal.Type.forType(mealType.toUpperCase());
Meal.Flavor flavor = Meal.Flavor.forFlavor(flavorValue.toUpperCase());
if (type != null && flavor != null) {
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
Collections.shuffle(matchingMeals);
Meal meal = matchingMeals.get(0);
System.out.println(meal.getDescription());
} else {
if (type == null) {
System.out.println(mealType + " is not a valid type");
}
if (flavor == null) {
System.out.println(flavorValue + " is not a valid flavor");
}
}
to look up a random meal.
Now, because you should be running in Java 8+, you could also replace...
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
with...
Predicate<Meal> filter = meal -> meal.matches(type, flavor);
meals.stream().filter(filter).collect(Collectors.toList());
but that might be a bit of an ask
Map
Or, we can use a Map of some kind to link the List of data with a specific "key".
Since you have a "composite" key style (you strictly don't need to, but I like having the flavour and type separated), I started with a MealKey concept.
public class MealKey {
private Type type;
private Flavor flavor;
public MealKey(Type type, Flavor flavor) {
this.type = type;
this.flavor = flavor;
}
#Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + Objects.hashCode(this.type);
hash = 97 * hash + Objects.hashCode(this.flavor);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MealKey other = (MealKey) obj;
if (this.type != other.type) {
return false;
}
if (this.flavor != other.flavor) {
return false;
}
return true;
}
}
The important thing here is to ensure that any instance of a key with the same type/flavor always returns the same hashCode
I then modified the POJO to make it simpler/easier to deal with...
public enum Type {
BREAKFAST, LUNCH, DINNER;
public static Type forType(String value) {
try {
return Type.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public enum Flavor {
SWEET, SAVORY;
public static Flavor forFlavor(String value) {
try {
return Flavor.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public class Meal {
private String description;
public Meal(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
Then we fill our Map with the values we want
Map<MealKey, List<Meal>> meals = new HashMap<>();
// Fill the meals
List<Meal> breakfastSweet = new ArrayList<>();
// Add some meals to the list
meals.put(new MealKey(Type.BREAKFAST, Flavor.SWEET), breakfastSweet);
And then we can look up the meals list based on the user input...
// Get user input
Type type = Type.forType(mealType.toUpperCase());
Flavor flavor = Flavor.forFlavor(flavorValue.toUpperCase());
if (type != null && flavor != null) {
MealKey key = new MealKey(type, flavor);
List<Meal> mealsList = meals.get(key);
if (mealsList != null) {
Collections.shuffle(mealsList);
System.out.println(mealsList.get(0).getDescription());
}
} else {
if (type == null) {
System.out.println(mealType + " is not a valid type");
}
if (flavor == null) {
System.out.println(flavorValue + " is not a valid flavor");
}
}
nb: You could simply the "key" by simply using a String of "type" + "value" if you really wanted to 😉
I would rely on Map as the way to structure your data:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
// list of meals, list name describes
Map<String, Map<String, List<String>>> meals = new HashMap<>();
Map<String, List<String>> breakfast = new HashMap<>();
breakfast.put("sweet", new ArrayList<>());
meals.put("breakfast", breakfast);
// The same for the following:
// - lunch --> sweet --> list
// - lunch --> savory --> list
// - dinner --> sweet --> list
// - dinner --> savory --> list
GetRandomFromList.outputMeal(mealType, flavor, meals);
}
}
And then your GetRandomFromList would be simpler:
public class GetRandomFromList {
private static String randomList(List<String> list) {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
public static void outputMeal(String mealType, String flavor, Map<String, Map<String, List<String>>> meals){
Map<String, List<String>> meal = meals.get(mealType);
if (meal.isEmpty()) {
System.out.println("No possibilities found");
} else {
List<String> mealFlavourPossibilities = meal.get(flavor);
if (mealFlavourPossibilities.isEmpty()) {
System.out.println("No possibilities found");
} else {
System.out.println("What about " + GetRandomFromList.randomList(mealFlavourPossibilities) + "?");
}
}
}
}

string choice condition is met, class is not called

EDIT again:
each time I run this and input the "String a", all methods get called and I don't know why.
I know its all newbie stuff but counter intuitively, there are too many tutorials and threads on java to properly troubleshoot basic issues like this.
import java.util.*;
public class ShopTest {
public static Scanner navigate = new Scanner(System.in);
public static Scanner playerStats = new Scanner(System.in);
public static Scanner shop = new Scanner(System.in);
static int playerGold = 0;
static String items;
static int ironSword = 200;
static int rustySword = 75;
static int lightLeatherArmor = 50;
static int minorHealthpotion = 25;
static String bought = "item added to inventory";
static String notBought = "Sorry, you don't have enough for that!";
public static void main(String[] args) {
System.out.println("Welcome player.\nWhat is your name?");
String playerName = playerStats.next();
System.out.println("\nAh!" + playerName + "\n\nWe've been expecting you.\nAs we agreed, you get half the gold now and half after you kill that goblin!\nYou recieved 150 gold.");
playerGold = playerGold +150;
Navigate();
}
public static void Shop() {
System.out.println("\nWelcome to my shop\nWould you like to see my wares?");
String shopChoice1 = shop.next();
if (shopChoice1.equals("yes")) {
System.out.println("\nSee anything you need?\nIron sword: " + ironSword + "\nRusty sword: " + rustySword + "\nLight leather armor: " + lightLeatherArmor + "\nMinor health potion: " + minorHealthpotion);
}
String shopChoice2 = shop.next();{
System.out.println("ok");
if (shopChoice2.equals("iron sword")) {
IronSword();}
else if (shopChoice2.equals("rusty sword")) {
RustySword();}
else if (shopChoice2.equals("light leather armor")) {
LightleatherArmor();}
else if (shopChoice2.equals("minor health potion")) {
MinorhealthPotion();}
else if (shopChoice2.isEmpty()) {
Shop();}
}
}
public static void IronSword() {
if (playerGold >= ironSword)
System.out.println(bought);
items = items + "Iron sword,\n";
if (playerGold < ironSword)
System.out.println(notBought);
Shop();
}
public static void LightleatherArmor() {
}
public static void RustySword() {
if (playerGold >= rustySword)
System.out.println(bought);
items = items + "Rusty Sword,\n";
if (playerGold < rustySword)
System.out.println(notBought);
Shop();
}
public static void MinorhealthPotion() {
}
public static void Inn() {
System.out.println("**You enter the inn and approach the barkeep**\nHow can I help you?");
}
public static void Inventory() {
System.out.println("Gold: " + playerGold + "\nItems: \n" + items + "\n\n");
Navigate();
}
public static void Navigate() {
System.out.println("\nWhat next?\n Shop\n Inn\n Inv");
String a = navigate.nextLine();
if (a.equals("shop"))
Shop();
else if (a.equals("inn"))
Inn();
else if (a.equals("inv"))
Inventory();
}
}
*need add more text for some reason!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*need add more text for some reason!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*need add more text for some
The default delimiter for the Scanner is whitespace. Which means it will break up the string on every whitespace (space, tabs, newlines). So if you enter "iron sword" you will only get "iron" on shop.next() and "sword" on the call after.
Since you want to read in whole lines, you can set the Delimiter to a newline. Like this:
public static Scanner shop = new Scanner(System.in).useDelimiter("\\n");
The Javadoc for the Scanner class mentions this: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
BTW: Which IDE do you use? If you are new to programming make yourself familiar with it's debugging features. You can set a breakpoint right after the shop.next() call and then inspect the content of shopChoice2. This would have shown you that shop.next() does not do what you expect it to do.
EDIT:
There is a mistake after you edited your code:
if (shopChoice2.equals("iron sword"))
System.out.println("ok");
IronSword();}
if (shopChoice2.equals("rusty sword"))
This should be:
if (shopChoice2.equals("iron sword")) {
System.out.println("ok");
IronSword();}
} else if (shopChoice2.equals("rusty sword"))
Only "System.out.println("ok");" is being called if the if statement is true. Note that only the next statement is called if an "if" statement is true. If you need more that one statement to be executed you need to enclose those in curly brackets. As a general rule one should ALWAYS use curly brackets with if statements. Even if there is only one statement. This helps avoiding making mistakes like that.
EDIT 2:
This should work. Find the differences to your code:
String shopChoice2 = shop.next();
System.out.println(shopChoice2);
if (shopChoice2.equals("iron sword")) {
IronSword();"
} else if (shopChoice2.equals("rusty sword")) {
RustySword();
} else if (shopChoice2.equals("light leather armor")) {
LightleatherArmor();
} else if (shopChoice2.equals("minor health potion")) {
MinorhealthPotion();
} else if (shopChoice2.isEmpty()) {
Shop();
}

Endless loop while validating user input

I'm trying to validate german postcodes in a input form.
But somehow i get stuck in line 15 and my function is just printing "Give me input" in an endless loop.
I expected that sc_plz.nextLine() would be a blocking function but somehow it's not.
import View.AddressView;
import java.io.IOException;
import java.util.Scanner;
public class AddressController {
AddressView view = new AddressView();
public Address addAddress()throws IOException{
//other input questions
Scanner sc_plz = new Scanner(System.in);
int code = 0;
while (!validatePostcode(code))
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
}
catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
//other input questions
}
private boolean validatePostcode(int plz) throws IOException {
//legal postcodenumbers are between 01000 -99999
if (1000 <= plz && plz <= 99999){
return true;
}
else {
return false;
}
}
}
Did you forget brackets for your while statement? As it is right now it will always do whatever is in view.askPostcode();. I imagine this is what it should look like:
while (!validatePostcode(code)) {
view.askPostcode(); //simple System.out.println("Input something")
String postcode = sc_plz.nextLine();
try {
code = Integer.parseInt(postcode);
} catch (NumberFormatException e){
view.invalidData(); //warning about not got a number
}
}

Java - iteration of an array list with case of no found

I write this code who iterate an arraylist and if found a name who's equal to getName it's will print that and if not found will print "a message". My problem with this code is:
if a person have same nome of another persone the program will stop at first match because of break; how can i fix that?
import java.util.*;
public class AggPersone {
public static void main(String[] args) {
ArrayList<Item> voce = new ArrayList<Item>();
voce.add(new Item("Robert", "Via qualcosa", "123"));
voce.add(new Item("Roberto","Via qualcosina", "123"));
voce.add(new Item("Robert", "Via qual ", "2222"));
Scanner input = new Scanner(System.in);
System.out.println("chi cerchi?");
String chiave = input.nextLine();
int i = 0;
while(i < voce.size()){
if(voce.get(i).getNome().equals(chiave)){
System.out.println(voce.get(i).toString());
break;
}
i++;
if(i == voce.size()){
System.out.println("Nessun match");
}
}
input.close();
}
}
Use a boolean variable to flag if the name has been found:
boolean found = false;
for (Item item : voce) {
if(item.getNome().equals(chiave)){
System.out.println(item.toString());
found = true;
}
}
if (!found) {
System.out.println("Nessun match");
}

Categories