I want my program to keep asking the question until it gets a response it can use, specifically a number from 0 to 20. I have a lot of other stuff on this class, so here is a small excerpt where the do-while is (I have named the variables and all that for everything).
public static void main(String[] args) {
do {
halp = 1;
System.out.println("What level is your fort?");
Scanner sc = new Scanner(System.in);
try {
fortLevel = Integer.parseInt(sc.nextLine());
}
catch(NumberFormatException e){System.out.println("Numbers only, 0-20"); halp = 0;
}
if(halp < 1) {
work = false;
}
if(halp > 1) {
work = true;
}
while(work = false);
}
while(work = false); // here you are assigning false to work
should be
while(work == false); //here you are checking if work is equal to false
= an assignment operator used to assign value
== an equality operator used to check if two operands have same value.
As work is boolean you could even just use this:
while(!work)
You are using an assignment in your while expression:
while(work = false);
You can replace with
while(work == false);
or better
while(!work);
If variables halp and work are not used anywhere else, they could be eliminated giving you:
do {
System.out.println("What level is your fort?");
Scanner sc = new Scanner(System.in);
try {
fortLevel = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
System.out.println("Numbers only, 0-20");
}
} while (fortLevel < 0 || fortLevel > 20);
You could also do this:
if(!work) {break;}
Related
So as the title says im struggling to add a value to an integer and then pass it to another class that uses it, then this class will pass it to the next and then that one will pass it over to the main class. Its an integer that changes the stat template of the enemies in my small game im writing.
I have tried to make constructors in two of my classes as I thought that was the problem, Ive tried to see if they work by passing some messages in them.
The problem seems to be that when I save something in the "private int l" It dosnt actually change the value of that int and I cant figure out why that is.
Here is my code, its probably not very pretty so if you have any suggestions to structure changes that I might wanna do please feel free too let me know!
Thanks in advance!
import java.util.Scanner;
public class Stor {
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
EnemyValue monster = new EnemyValue();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty();
System.out.println(“Your enemy has " + monster.HP + " HP and " +
monster.DMG + " Damage" );
user_Input.close();
}
}
class Menu {
Scanner user_Input = new Scanner(System.in);
String AnvNamn;
String difficultySvar;
String nivåSvar;
int svar;
private int i; /
private int l;
public int getL() {
return l;
}
boolean difficultyLoop = true;
boolean felLoop = true;
void introMeny() {
System.out.println(“Welcome " + AnvNamn + "!");
}
void namn() {
System.out.print(“Pick a name: “);
}
void difficulty() {
do {
System.out.println("\nWhat level do you want ?\n1 = Easy.\n2 =
Medium.\n3 = Hard.”);
svar = user_Input.nextInt();
if (svar == 1) {
System.out.println(“Your not very brave are you ? Are you sure
this is how you wanna play ?”);
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 1;
} // If ja 1
else if (difficultySvar.equalsIgnoreCase(“Nej”)) {
System.out.println(“Ahh good! I figuerd you would change
your mind.”);
}
else
System.out.println(“I don’t understand….”);
} // if 1
else if (svar == 2) {
System.out.println(“Not to hard or to easy, a good choice! But
maybe you want to go for something harder ? Or maybe easier ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 2;
} // if ja 2
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“I sure hope you don’t pick the easy
way…..”);
}
else
System.out.println("I don’t understand….");
} // Else if 2
else if (svar == 3) {
System.out.println(“Damn! We have a big player here! Are you
sure you can handle this ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 3;
} // If ja 3
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“Wuss.”);
}
else
System.out.println(“I don’t understand….”);
} // Else if 3
else {
if (i == 0) {
System.out.println(“Ha you thought you could fool the system?!
The system fools you!”);
System.out.println(“Nah but seriously, you can only choose
between 1-3…..“);
i++;
} // if i 0
else if (i == 1) {
System.out.println(“Alright I get that its hard but
COMEON!”);
i++;
} // if i 1
else if (i == 2) {
System.out.println(“OKEY YOU GET ONE LAST CHANCE!!”);
i++;
} // if i 2
else if (i == 3) {
System.out.println(“Alright thats it…. GET OUT!”);
System.exit(0);
} // if i 3
} // Else
} // do while loop
while(difficultyLoop == true);
} //Difficulty metod.
} // Menu class.
class Nivå {
//Menu level = new Menu();
//int levelChoice = level.getL();
int levelChoice;
private int enemyLife;
public int getenemyLife() {
return enemyLife;
}
private int enemyDMG;
public int getenemyDMG() {
return enemyDMG;
}
Nivå(){
Menu level = new Menu();
levelChoice = level.getL();
System.out.println("testNivå");
}
void fiendeLiv() {
if (levelChoice == 1)
enemyLife = 100;
else if (levelChoice == 2)
enemyLife = 150;
else if (levelChoice == 3)
enemyLife = 200;
} // fiendeliv method
void fiendeDMG() {
if (levelChoice == 1)
enemyDMG = 5;
else if (levelChoice == 2)
enemyDMG = 10;
else if (levelChoice == 3)
enemyDMG = 15;
} // fiendeDMG method
} // Nivå class
class EnemyValue {
public int HP;
public int DMG;
int maxLife;
int maxDMG;
EnemyValue(){
Nivå stats = new Nivå();
maxLife = stats.getenemyLife();
maxDMG = stats.getenemyDMG();
System.out.println("TestEnemyValue");
}
void rank1() {
HP = maxLife;
DMG = maxDMG;
} // rank1 easy method
} // EnemyValue class
You say that when you save something in l (poor choice of a variable name, by the way) it does not save the value. How do you know that? Where in the code do you check whether the value is saved?
In the constructor for class Nivå you create a new Menu and then call getL() on that menu before you have ever set the value of that variable.
Everything runs at the start of your public static void main(String[] args) method, and nothing will run if its instructions are not in there. For example, you are not actually creating any Niva objects in the main method, so the Niva constructor is never called. That is one issue. The other is your constructors are creating new instances of objects and then getting their values; this gives you empty values from a brand new object:
Nivå(){
Menu level = new Menu(); // Don't do this. This is an empty menu
levelChoice = level.getL(); // Getting the blank L value from the empty menu
System.out.println("testNivå");
}
Instead, you need to define constructors with parameters to pass the values into the class like this:
Nivå(int level){ // add an int parameter
levelChoice = level; // Direct assignment
fiendeDMG(); // Call this in the constructor to set up your last value
System.out.println("testNivå");
}
Then, when you call the constructor (which you must if you want it to exist), include the parameter. Inside the Stor class:
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty(); // Run this before creating the other classes; you need the l value
Nivå niva = new Nivå(user.getL()); // Creates new Niva while also assigning l to the levelChoice and then getting DMG
EnemyValue monster = new EnemyValue(/*add some parameters for life and dmg*/);
}
There is still more that needs to be done, like modifying the constructor of the EnemyLevel. Just remember that methods are never called unless they connect to something running from main and use parameters in functions and constructors to pass on data to other objects. Hope this helps.
I wanted to make an input which accepts numbers from 1 - 10 and prints the range.
I need to check if the input is an integer (check), check if the range is 0-10 (check), and if it's not any of those things, to ask the user again. So, a recursive method?
Currently I have this:
import java.util.Scanner;
import java.util.InputMismatchException;
public class FinalTest {
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
int k = 0;
System.out.print("int - ");
try {
k = in.nextInt();
} catch (InputMismatchException e) {
System.out.println("ERR: Input");
System.exit(1);
}
if(k <= 10 && k > 0) {
for(int j=1; j <= k; j++) {
System.out.println(j);
}
} else {
System.out.println("ERR: Oob");
System.exit(1);
}
}
}
I would like to replace the "System.exit()" so that it re attempts to ask the user for input again.
calling main(); produces an error.
How do I correctly call the main method in this case?
Two choices here:
actually create a method and call that
simply use a loop
Loop could go like:
boolean askForInput = true;
while ( askForInput ) {
try {
k = in.nextInt();
askForInput = false;
} catch ...
print "not a number try again"
}
But beyond that: you still want to put this code into its own method. Not because that code should call itself, but for clarity reasons. Like:
public static int askForNumber(Scanner in) {
... code from above
return k;
}
And to answer your question: you do not want to use recursion here. You want to loop; and yes, recursion is one way to implement looping, but that is simply overkill given the requirement you want to implement here.
And for the record: when creating that helper method, you can actually simplify it to:
public static int askForNumber() {
while ( askForInput ) {
try ...
return in.nextInt();
} catch ...
print "not a number try again"
}
}
Beyond that: you typically use recursion for computational tasks, such as computing a factorial, or fibonacci number, ... see here for example.
for the part of the recursive method printing a range:
public void printAscending(int n) {
if (n > 0) {
printAscending(n - 1);
System.out.println(n);
}
}
I think using recursion is just too much for something that simple and would probably be more expensive. You can add a while loop around your scanning bit until the entered value is valid. I would also put the printing loop out of the while to not have to test a condition before printing since if you get out of the while loop, it means number if valid. You could test just the -1 value to exit process.
public class FinalTest
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int k = 0;
do
{
System.out.print("int - ");
try
{
k = in.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("ERR: Input");
System.exit(1);
}
}
while(!(k>0 && k<=10) && k!=-1);
if(k!=-1)
{
for(int j=1; j<=k; j++)
{
System.out.println(j);
}
}
else
{
System.out.println("Bye Bye.");
}
}
}
Okay, so what I personally do when I need to use recursion is I create a separate function/method for it. And when I need to restart the method, I just call it within itself. So it would be something like this:
private void recursiveMethod() {
// do stuff . . .
if (yourCondition) {
//continue to next piece of code
} else {
recursiveMethod();
}
}
But in big projects, try to stay away from recursion because if you mess up, it can
I am trying to execute a program after taking user input from the console. [code block below]. However, I do not want to terminate after the program execution finishes. I want the console to always ask me the INITIAL_MESSAGE after the execution finishes. Effectively, after the execution of the program, I want the console to again ask me the INTIAL_MESSAGE so that I can again enter the inputs as I want and execute the program again.
I am actually calling the interactor() in this method, from the main method as the starting point.
Please tell me how do I achieve this
public class ConsoleInteraction {
/**
* #param args
*/
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
Barracks trainingBarrack = new Barracks();
public void interactor() throws IOException {
//reading capability from the consolemessages properties file
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
// Create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference
if(preference == 1)
{
//System.out.println("Whom do you want to train?\n 1.Java Guy \n 2.PHP Guy \n 3.Mix \n Enter You preference:");
System.out.print(bundle.getString("WHO_TO_TRAIN"));
int traineepreference = scanner.nextInt();
if (traineepreference == 1)
{
//System.out.println("How many Java guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, 0);
}
else if (traineepreference == 2)
{
//System.out.println("How many PHP guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(0, numberOfPHPTrainees);
}
else if (traineepreference == 3)
{
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, numberOfPHPTrainees);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE1"));
}
}
else if (preference == 2)
{
System.out.println("Showing Camp to You");
System.out.println("Java trained in Trainee Camp : "+ TraineeCamp.trainedJavaGuys);
System.out.println("PHP trained in Trainee Camp : "+ TraineeCamp.trainedPHPGuys);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
scanner.close();
}
}
Consider these changes quickly drafted to your class. Might not compile. Might not work as you planned.
Some highlights of what I think you should change:
Use constants for the choice values. Makes your code way more better to read.
Initialize Bundle and Scanner outside of the method. Might be reused.
instead of coding lengthy parts of code inside of the if-else-if cascade, call methods there - angain increasing your readability a long way
public class ConsoleInteraction {
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
//Don't read that every time...
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
public static void main(String[] args) {
//Moving Scanner out of loop
try {
Scanner scanner = new Scanner(System.in);
ConsoleInteraction ci = new ConsoleInteraction();
//Loop until this returns false
while(ci.interactor(scanner)) {
System.out.println("=== Next iteration ===");
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Constant values to make code readable
public final static int PREF_TRAINING = 1;
public final static int PREF_SHOW_CAMP = 2;
public final static int PREF_QUIT = 99;
public boolean interactor(Scanner scanner) throws IOException {
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference.
if(preference == PREF_TRAINING) {
//LIKE YOU DID BEFORE OR calling method:
readTraining(scanner);
} else if (preference == PREF_SHOW_CAMP) {
//LIKE YOU DID BEFORE OR calling mathod:
showCamp();
} else if (preference == PREF_QUIT) {
//Last loop
return false;
} else {
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
//Next loop
return true;
}
}
I have a guessing program, and Im trying to add a counter. In the bolded parts I have a counter. When you get a guess wrong, it adds 1 to the counter. But when it prints it, it just prints as 0 no matter what.
public static void firstGame(String Answer, String userGuess, int counter)
{
userInput = new Scanner(System.in);
boolean playgame = true;
while(playgame == true)
{
Answer = "Sam";
lnPrint(" ");
lnPrint("Take a guess at my name! It starts with an S...");
sPrint(":");
userGuess = userInput.next();
if(userGuess.equalsIgnoreCase(Answer))
{
lnPrint("You got it! Its " + Answer);
lnPrint(" ");
break;
}
else if(userGuess != Answer)
{
lnPrint("Good guess, keep trying!");
counter++;
}
}
}
That is my game method with the counter.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
int Start, counter = 0;
String Answer, userGuess, middleAnswer, middleUserGuess;
Answer = null;
userGuess = null;
middleAnswer = null;
middleUserGuess = null;
Start = 0;
while(Start !=2)
{
lnPrint("(1) Start Game");
lnPrint("(2) Exit");
sPrint(":");
Start = userInput.nextInt();
if(Start == 1)
{
firstGame(userGuess, Answer, counter);
lnPrint("Now, how about my middle name?");
nlnPrint(counter);
middleGame(middleAnswer, middleUserGuess);
}
This is the code that prints it
This looks like a common pass by value / reference problem. When using counter as an argument for firstGame, it's the value of counter that is used in the firstGame method, as opposed to passing a reference to the counter variable; you can read about this here, for example: http://www.javacoffeebreak.com/faq/faq0066.html
There are ways of passing integers by reference to methods (see Java : Best way to pass int by reference) but in this case I think you should simply declare counter as a global variable.
Have you initialized "counter" earlier?
Heres an example where it works:
$.Guess = function() {
var parent = this;
var counter = 0;
this.guess = function(val) {
if ( val != 5 ) {
parent.guessedWrong();
}
}
this.guessedWrong = function() {
counter++;
}
this.guessed = function() {
return counter;
}
this.resetCounter = function() {
counter = 0;
}
}
var game = new $.Guess();
game.guess(1);
game.guess(2);
alert( game.guessed() );
game.guess(3);
game.guess(4);
game.guess(5);
// Alerts 4, because there is 5 guesses and one of them (the one with value 5) is correct
alert( game.guessed() );
// Reset counter to 0
game.resetCounter();
game.guess(6);
game.guess(7);
game.guess(8);
alert( game.guessed() );
..the code above can be tested here: http://jsfiddle.net/jcpjr9dc/
So my code is done, but now I need it to print out wether the chosen numbers are equal or not!
I've made a loop for FALSE / NUMBERS ARE EQUAL, but it doesn't work properly.
Hope you can help.
My code looks like this:
package patternrecognition;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
public class PatternRecognition {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int AntalNumre = -1;
boolean Gyldignummer = false;
while (Gyldignummer == false) {
System.out.print("\n\nIndtast antal numre: ");
String numre = reader.readLine().trim();
Gyldignummer = validInteger(numre);
if (Gyldignummer == false) {
System.out.println("Indtast et gyldigt nummer");
} else {
AntalNumre = Integer.parseInt(numre);
}
}
HashMap vaerdier = new HashMap();
for (int i = 0; i < AntalNumre; i++) { //Studerendes nummer(i+1)
boolean GyldigNummer2 = false;
while (GyldigNummer2 == false) {
System.out.print("\n\nIndtast en vaerdi for nummer " + (i + 1) + ": ");
String vaerdi = reader.readLine().trim();
int vaerdien = -1;
GyldigNummer2 = validInteger(vaerdi);
if (GyldigNummer2 == false) {
System.out.println("Indtast et gyldigt nummer");
} else {
vaerdien = Integer.parseInt(vaerdi);
}
vaerdier.put(vaerdi, new Integer(vaerdien));
}
}
TreeMap SorteretNummer = new TreeMap(vaerdier);
Iterator nr = SorteretNummer.keySet().iterator();
System.out.println("\n\n\n\n\n");
System.out.println("Numre valgt:");
System.out.println("------------");
while (nr.hasNext()) {
String navn = (String) nr.next();
int numre = ((Integer) SorteretNummer.get(navn)).intValue();
System.out.println("" + numre);
if (numre != numre) {
System.out.println("FALSE");
}
else {
System.out.println("ALLE THE NUMBERS ARE EQUAL");
}
}
}
public static boolean validInteger(String nummer) {
boolean validInteger = false;
try {
Integer.parseInt(nummer);
validInteger = true;
} catch (NumberFormatException nfe) {
validInteger = false;
}
return validInteger;
}
}
Well, numre != numre is bound to be false unless of course numre happens to be changed in another thread (or be NaN, but that's a different story).
Perhaps, you may want to compare pairs of numbers? Or, perhaps, you want to have a data structure holding the numbers you've already seen (e.g. HashSet or BitSet)?
An example: as user enters numbers, save those to a HashSet<Integer>. As soon as he's done, add
Set<Integer> set = new hashSet<Integer>();
// ...as we're getting numbers from user
set.add(numre);
// ...
if (set.size() == 1)
System.out.println("OMG they're all the same! " + set);
This is a problem:
if (numre != numre) {
System.out.println("FALSE");
}
else {
System.out.println("ALLE THE NUMBERS ARE EQUAL");
}
Comparing the same variable to itself: will always print "ALLE THE NUMBERS ARE EQUAL".
EDIT:
Remember the previously entered Integer and compare to the most recently entered Integer. Use Integer and initialise the previousInt to null so you know to avoid comparison on initial loop iteration.
As it is homework I will not post the code and it will be more benefit to you if you code it yourself.