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();
}
Related
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);
}
}
So I am having an issue where I would like to create a record in one procedure, then alter the attributes of that record using other procedures and functions.
import java.util.Scanner; // Imports scanner utility
import java.util.Random;
import java.lang.Math;
class alienPet
{
public void main (String[] param)
{
// We want to call all of the functions
// and procedures to make an interactive
// alien program for the user.
welcomeMessage();
alienCreation();
System.exit(0);
} // END main
/* ***************************************
* Define a method to obtain the users input
* and start the correct method.
*/
public static String userInput (String message)
{
Scanner scan = new Scanner(System.in);
String inp;
print(message);
inp = scan.nextLine();
return inp;
} // END userInput
/* ***************************************
* Define a method to print messages.
*/
public static void print (String message)
{
System.out.println(message);
return;
} // END print
/* ***************************************
* Define a method to
*/
public static void welcomeMessage ()
{
print("Thank you for playing the pet alien game");
print("In this game, you will have to look after your own alien.");
print("There is multiple aspects to looking after your alien, such as:");
print("Hunger, Behaviour and Thirst.");
print("");
print("When prompted, you can use the following commands:");
print("feed -> Replenishes alien to max hunger level");
print("drink -> Replenished thirst level to max");
print("");
return;
} // END
/* ***************************************
* Define a method to
*/
public void alienCreation ()
{
Alien ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation
public void alienBehaviour (int hunger) {
if (hunger <= 2){
print(ufo.name + " is very hungry, and is dangerously angry!!");
String action = userInput("You should feed it as soon as possible. (by typing 'feed')");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("That is a dangerous decision.");
}
}else if (hunger <= 4) {
print(ufo.name + " is mildly hungry, but is in a calm state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}else if (hunger <= 6) {
print(ufo.name + " is not hungry and is in a happy state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}
}
public void feedAlien() {
ufo.hungerRate = 6;
print(ufo.name + "'s hunger level replenished to max level 6.");
print(ufo.name + " is now at a happy level.");
}
public void alienDrink() {
ufo.thirst = 6;
print(ufo.name + "'s thirst level replenished to max level 6.");
}
public static int ranNum(int min, int max){ // A function that generates a random integer wihin a given range.
Random random = new Random();
return random.ints(min,(max+1)).findFirst().getAsInt();
} // END ranNum
} // END class alienPet
class Alien {
String name;
int age = 0;
int hungerRate;
int thirst = 6;
}
Obviously, some of the annotations are incomplete as of this time, but the issue I am having is in the alienBehaviour(), feedAlien() and alienDrink() procedures, I cannot seem to access the record created in the alienCreation() procedure.
The errors are all the same and is as follows:
alienPet.java:84: error: cannot find symbol
print(ufo.name + " is very hungry, and is dangerously angry!!");
^
symbol: variable ufo
location: class alienPet
Now I am new to java, so I'm not sure whether I have to make the record global or something, so any help would be greatly appreciated.
Variables declared inside of a method are called local variables and are likely disposed of when the method finishes executing.
Variables declared outside any function are called instance variables and they can be accessed (used) on any function in the program.
You are looking for an instance Alien ufo variable.
class alienPet{ // It is recommended you use the java naming convention.
Alien myAlien = new Alien();
// alienPet a = new alienPet();
// a.myAlien; // you could potentially do this to get an alien from an alienPet class
void someVoid(){
Alien otherAlien;
}
void errorVoid(){
otherAlien.toString();
// causes an error, the otherAlien variable is never visible to errorVoid as it is a local variable
myAlien.toString(); // OK
}
}
https://www.oracle.com/technetwork/java/codeconventions-135099.html
You're having problems with the scope of your variable. Variables are only valid within the curly braces which they were declared in.
WRONG
public void alienCreation ()
{
Alien ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation and of the scope of your variable ufo
RIGHT
class alienPet
{
Alien ufo;
[...]
public void alienCreation ()
{
ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation and your variable ufo will be initialized afterwards
}
I am trying to add a header to the beginning of each page in Java. I am printing my console output to a file as well. All of the examples I can find are for PDF files but I need to print to a text file for later data transfer and use iText which I cannot use. Any suggestions would be awesome. Here is how I am printing so far:
PrintStream out = new PrintStream(new FileOutputStream("example.txt"));
System.setOut(out);
I'm assuming you're going to use fixed-width characters (anything else would be significantly more complicated..)
Here is a naive implementation, you can tweak it from here. I think it works pretty decently but you should test it thoroughly, also handle the case when a word is longer than a line and maybe a better exception for when a header is longer than the page:
public class PagePrinter {
private final PrintStream printer;
private final int pageWidth;
private final int pageLength;
private int currWidth = 0;
private int currLine = 0;
private int currPage = 1;
private boolean inPageHeader = false;
/**
* #param printer
* - print stream to print to
* #param pageWidth
* - in characters
* #param pageLength
* - in lines, includes the length of the header
*/
public PagePrinter(PrintStream printer, int pageWidth, int pageLength) {
this.printer = printer;
this.pageLength = pageLength;
this.pageWidth = pageWidth;
}
public void print(String str) {
// replace tabs with spaces
// may need to replace other chars that don't translate to 1 char when printed
str = str.replace("\t", " ");
// split would drop a trailing delimiter so concat extra
String[] lines = str.concat("\r\n#").split("\\r?\\n");
// print first
printWords(lines[0]);
// print rest excluding the extra
for (int i = 1; i < lines.length - 1; i++) {
// re-add delimiter (but keeping track of its affect on the page)
newline();
printWords(lines[i]);
}
}
private void printWords(String str) {
// split would drop a trailing delimiter so concat extra
String[] words = str.concat(" #").split(" ");
printWord(words[0]);
for (int i = 1; i < words.length - 1; i++) {
// re-add delimiter (but keeping track of its affect on the page)
if (currWidth < pageWidth) {
printer.print(" ");
currWidth++;
}
printWord(words[i]);
}
}
/** The smallest unit of appending to the document, */
private void printWord(String word) {
// determines when to print a header
if (currLine == 0 && !inPageHeader) {
printPageHeader();
}
int remainingSpaceOnLine = pageWidth - currWidth;
if (word.length() < remainingSpaceOnLine) {
printer.print(word);
currWidth += word.length();
} else if (word.length() < pageWidth) {
newline();
printWord(word);
} else {
// FIXME word is longer than the page width
// maybe split it with a hyphen and addWord() the parts
throw new RuntimeException("Word '" + word + "' is longer than line!");
}
}
public void newline() {
currLine++;
if (currLine >= pageLength) {
newPage();
} else {
currWidth = 0;
printer.println();
}
}
public void newPage() {
if (inPageHeader) {
throw new RuntimeException("Page header is longer than the page!!!");
}
currWidth = 0;
currLine = 0;
currPage++;
printer.println();
}
private void printPageHeader() {
inPageHeader = true;
myPageHeader();
inPageHeader = false;
}
protected void myPageHeader() {
print("----- Page " + currPage + " -----\n");
}
public static void main(String[] args) {
PagePrinter test = new PagePrinter(System.out, 40, 10);
test.print("\tThis is the song that never ends. Yes, it goes on and on my friend. "
+ "Some people started singing it not knowing what it was "
+ "and they'll continue singing it forever just because..."
+ "\n\tThis is the song that never ends. Yes, it goes on and on my friend. "
+ "Some people started singing it not knowing what it was "
+ "and they'll continue singing it forever just because..."
+ "\n\tThis is the song that never ends. Yes, it goes on and on my friend. "
+ "Some people started singing it not knowing what it was "
+ "and they'll continue singing it forever just because.."
+ "\n\tThis is the song that never ends. Yes, it goes on and on my friend. "
+ "Some people started singing it not knowing what it was "
+ "and they'll continue singing it forever just because...");
test.newPage();
test.print("This is a new page!");
test.newline();
test.print("This is a newline even though part would've fit on the previous!");
}
}
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.
It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
I currently have no errors my only problem is that I do not know how to add men to my regiment. I have to use the addMen method in the army class which I currently have blank.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
public String getName() {
return name;
}
public int getregNumber() {
return regNumber;
}
public int getMen() {
return men;
}
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
ArmyDataList:
class ArmyDataList {
public ArrayList<Regiment> list;
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
public void AddToList(Regiment current) {
list.add(current);
}
public void RemoveFromList(Regiment current) {
list.remove(current);
}
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
public void addMen() {
}
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
RegimentTest:
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
Add a setMen(int numberOfMen) method to your Regiment class. Then in your addMen() method, you can do something like this:
public void addMen(){
for(Regiment r : list){ //iterate through the list of regiments
r.setMen(r.getMen() + 100); //add 100 men to each regiment
}
}
The setMen method would look like this:
public void setMen(int numberOfMen){
men = numberOfMen;
}
There is another issue with your toString method, where the regiment's addMen2 method is called - right now you're just printing the number, not initializing the number of men. In the constructor for your Regiment class, replace the line
this.men = men;
with
this.men = addMen2(regNumber);
Then in your toString method, replace
int men = regim.addMen2(regNumber);
with
int men = regim.getMen();
Here is what your main should look like:
public static void main(String[] args) throws IOException{
ArmyDataList army = new ArmyDataList();
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line);
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder);
}
System.out.println(army.toString()); //print out the initial # of men
for(int i = 0; i < 20; i++)
army.addMen();
System.out.println(army.toString()); //print the final # of men
}
in Regiment get rid of method addMen2, and replace it with
public void addMen(int men) {
this.men +=men;
}
then in your army you could have method
public void addMen(int men) {
for(Regiment regiment : list){
regiment.addMen(men);
}
}
that will be simplest solution to add 100 men to each regiment,
other thing is, your toString is bit nasty, regiment should know how meny soldiers it ghas, you shouldnt need additional method to calculate it (reason why i recommend you to trash addMen2 method)
to initiate your Regiment, use constructor. You want to have regiments in sizes 1000, 1950, 1900 etc, do it when you are creating them
while (fileScan.hasNext()) {
String line = fileScan.nextLine();
System.out.println(line);
Scanner in = new Scanner(line) ;
int regNumber = in.nextInt();
String name = in.next();
int men = 1050 - (regNumber * 50);
Regiment adder = new Regiment(regNumber, name, men );
army.AddToList(adder) ;
}