for loop for inputting variables into array not working? - java

I'm trying to input 3 different variables into an array inside a while loop, as long as i don't enter stop for any of the variables. the while loop is only suppose to let me input a second variable value if the 1st variable isn't stop, and likewise with inputting a third variable value
Right now, the first loop goes fine and i can input all 3 variables, but the 2nd and 3rd time, the for loop outputs the first variable, but doesn't allow me to input a value before skipping to the 2nd variable.
ex of what i mean:
name:afasdf
extra info:afdsaf
unit cost:123123214
name: extra info: adflskjflk
also, entering Stop isn't ending the loop either
unit cost:123217
i know that this loop works when there's only one variable, and i've tried using a for loop instead of a while loop, and adding tons and tons of else statements, but it seems to stay the same
is there something wrong with the way i set up my breakers?
is the way i set up the last breaker(the one that stops even when i put stop for a double variable) messing up the rest of hte loop?
thank you so much
here is my code
ArrayItem s = new ArrayItem();
String Name = null, ID = null;
double Money = 0;
boolean breaker = false;
while(breaker ==false)
{
System.out.print("Name:" + "\t");
Name = Input.nextLine();
if(Name.equals("Stop")) //see if the program should stop
breaker = true;
System.out.print("Extra Info:" + "\t");
Details = Input.nextLine();
if(ID.equals("Stop"))
breaker = true;
System.out.print("Unit Cost:" + "\t");
Money = Input.nextDouble();
// suppose to let me stop even if i input stop
// when the variable is suppose to be a double
if(Input.equals("stop") || Input.equals("stop"))
breaker = true;
else
s.SetNames(Name);
s.SetInfo(Details);
s.SetCost(Money);
}

A couple of things about the code: "Name:" + "\t" can be simplified ot "Name:\t". This is true for the rest of the code. In Java, it's customary to use camelcase where the first word is lowercase. For example, s.SetMoney would be s.setMoney. Also, variables follow the same rules where Money would be money, and ID would be id. If your teacher is teaching you otherwise, then follow their style.
The loop should also be a do-while loop:
do
{
// read each value in sequence, and then check to see if you should stop
// you can/should simplify this into a function that returns the object
// that returns null if the value should stop (requiring a capital D
// double for the return type)
if ( /* reason to stop */)
{
break;
}
s.setNames(name);
s.setId(id);
s.setMoney(money);
} while (true);
private String getString(Scanner input)
{
String result = input.nextLine();
// look for STOP
if (result.equalsIgnoreCase("stop"))
{
result = null;
}
return result;
}
private Double getDouble(Scanner input)
{
Double result = null;
// read the line is a string looking for STOP
String line = getString(input);
// null if it's STOP
if (line != null)
{
try
{
result = Double.parseDouble(line);
}
catch (NumberFormatException e)
{
// not a valid number, but not STOP either!
}
}
return result;
}
There are a lot of concepts in there, but they should help as you progress. I'll let you put the pieces together.
Also, you did need to fix the brackets, but that's not the only issue. Because Money is a double, you must read the value as a String. I suspect that Input is a Scanner object, so you can check Input.hasNextDouble() if it's not, then you can conditionally check the String value to see if it's "stop" (note: you are checking for "Stop" and "stop", which are not equal). Your last, no-chances check compares the Scanner to "stop", which will never be true. Check
System.out.print("Unit Cost:\t");
if (Input.hasNextDouble())
{
Money = Input.nextDouble();
// you can now set your object
// ...
}
// it's not a double; look for "stop"
else if (Input.nextLine().equalsIgnoreCase("stop"))
{
// exit loop
break;
}
// NOTE: if it's NOT a double or stop, then you have NOT exited
// and you have not set money

breaker = true;
while(breaker){
Name = readInput("Name");
Details = readInput("Details");
Money = Double.parseDouble(readInput("Money"));
if(Name.equals("stop") || Details.equals("stop"))
breaker = false;
else {
// set ArrayItem
}
}
private static String readInput(String title){
System.out.println(title+":");
//... read input
// return value
}

Related

How to iterate a condition in a while loop? Beanshell

Edited from my original post because I found a work around.
I'm trying to use a while loop to check if inputs exist. I have inputs that can vary in size, meaning I can have one input in a case or multiple in another. I'm using a while loop to execute many lines of code if the input(s) are present. The issue is that I know that I'll have at least one input in a case but in another case I may have 5,6,7, etc.
For example if I have:
input0="taco";
input1="water";
input2="sand";
With the example above in mind how do I iterate the condition of the while loop to make sure input0, input1, and input2 get executed?
In this example all of the commands within the while loop would be executed as long as input0,1,2 exist and are defined. My hope is that the integer q will scale with each input and the code within the while loop executes based on the current input.
When the loop reaches input3 I'd like it to exit the loop because that input does not exist.
I currently have the following:
int q=0;
String inputV =input(q);
while(inputV.contains("~")){ //first iteration takes "taco"
//This is where my long lines of code that need to be executed are
// I'm hoping that q will populate with 0,1,2 as the loop goes on and take "taco" "water" "sand" respectively
q++;
inputV=input(q);
//The next iteration will be input(1) = input1 which is "water"
}
New edit given the comment from Roger. The execution is having trouble getting through the if(f.equals(field)) statement. It passes through the for loop but can't process the if statement.
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
print(q + " " + inputV);
print("The input parameter is not null");
print("The input value is " + inputV);
// long lines of code executed within the while loop
q++;
inputV=input(q); }
You can find the defined variables in this.variables, global.variables or via the namespace.getVariableNames(). So with a helper method it is possible. In the example below I assumed they are defined in the global space.
input0="taco";
input1="water";
input2="sand";
String input(int q) {
String field = "input" + q;
for (String f: global.variables) {
if (f.equals(field)) {
return (String) this.namespace.getVariable(field);
}
}
return null;
}
int q=0;
String inputV = input(q);
while(inputV != null) {
System.out.println(q + " " + inputV);
q++;
inputV=input(q);
}
But, isn't there a better way for you to define the values such as array or list?

Do While Loop Error, Stuck in while loop

I have a boolean Guess function:
public boolean guess() {
String checkInput = scanner.nextLine();
try {
guess = Integer.parseInt(checkInput);
} catch (NumberFormatException e) {
return false;
}
return true;
}
which is called by another function in a do while loop:
while (!player.guess()) {
player.guess();
}
If I enter an int, the program runs properly and terminates. But if input is a non-int character, the program gets stuck in the while loop. I don't know what's going on here.
Your guess function is designed that way.
It returns false if the input is not numeric (catch). So it stays in the loop until you input a numeric value.
Another problem is that you are calling the function twice every loop (once on the loop condition check and another inside the loop). So if you type a non numeric character on the first (loop condition) and a numeric on the second (inside the loop) it will still ask for an input a third time.
I don't know what your intention is but you probably would want something like:
while (!player.guess()) {
continue;
}
Unless you really want it to be called twice.
Your scanner.nextLine() reads the line forever, it doesn't ask for another input.
while (!player.guess()) { // Entered Integer. (!true) and loop breaks
player.guess();
}
while (!player.guess()) { // Entered Non-Integer. (!false) and program enters the loop
player.guess(); // You are not storing the result in some boolean variable
//Therefore, it doesn't matter whether true or false
//while (!player.guess()) will be checked once again
}
SOLUTION:
boolean flag = player.guess(); // capture the result
while (!flag) { // verify the result
flag = player.guess(); // capture the result again
}

I'm having a hard time terminating a java loop

I'm sure if you read the snippet you'll understand what I'm trying to do. However, I tried it first with null and "". I think .eoln() won't work because I'm asking for multiple lines of input, of which all have an end of line. I would preferably have the loop terminate when the user returns an empty line. For some more background, I've used the ==/!= and .equals() operators/method to experiment. I also just tried a do/while to no avail.
The asterisks were added to test if the empty string was an issue for the while statement.
Can anyone explain what I clearly don't understand about Java/TextIO yet?
EDIT - Revised Code Snippet:
while(write){
pl("Begin writing content to fill file.");
pl("");
pl("Return a line with a single SPACE or");
pl("\"\\n\" to represent line breaks in your");
pl("");
pl("Return two asterisks ** when done writing,");
pl("and you will be then prompted to select a file");
pl("to save your writing to.");
String input = TextIO.getln();;
String value = new String();
while(!(input.equals(""))) {
if (input == " " || input == "\\n") {
value += "\\n" + "\\n";
} else {
value += input + " ";
} // end if/else //
input = TextIO.getln();
} // end while(input) //
TextIO.writeUserSelectedFile();
p(value);
TextIO.writeStandardOutput();
pl("Would you like to write to another file?");
Boolean cont = TextIO.getBoolean();
write = cont;
}
}

Assigning a String to a String array

I am trying to assign each string a user inputs to a String array. The entire thing is in a for loop and is evaluated by the index of the array. My code is:
String skillAssign[] = new String[100];
for (int i=0; isDone == false; i++)
{
System.out.println(skillAssign[i]);
System.out.println(i);
skillAssign[i] = keyboard.nextLine();
if ((!(skillAssign[i].equalsIgnoreCase("stats"))) && (!(skillAssign[i].equalsIgnoreCase("done"))))
{
assignmentValue = keyboard.nextInt();
if (((skillAssign[i].equalsIgnoreCase("health"))) && (skillPoints - assignmentValue >=0))
{
System.out.println("Added " + assignmentValue + " points to Health!");
skillPoints = (skillPoints - assignmentValue);
newMaxHealth = (assignmentValue + newMaxHealth);
}
//code that evaluates the string located inside the skillAssign[i] for other stats
}
The first string evaluates properly, but when I go to input the second string, I get java.util.InputMisMatchException. How can I get it so it assigns a string to each index of the array inputted by the user, then evaluate it? (I think I got the evaluation part though)
I tried to limit the post to relevant code, so things like isDone are omitted, but isDone is changed to true when done is typed and keyboard is constructed with Scanner keyboard = new Scanner all other variables are set to 0 except for skillPoints
I have tested the abovementioned code, and this is what happens:
We enter the loop.
You are requested to input the first string (through keyboard.nextLine()). I inputted 'health'.
You are requested to input an integer (through keyboard.nextInt()). I inputted '40'.
We re-enter the loop.
You are requested to input an integer (through keyboard.nextInt()).
...
It seems that I'm not asked to input the second string, but instantly the integer.
I do not know why it is, but it looks like nextInt() causes the next nextLine() to be skipped.
Maybe you can replace
assignmentValue = keyboard.nextInt();
with
try {
assignmentValue = Integer.parseInt(keyboard.nextLine());
}
catch (NumberFormatException exc) {
throw new InputMismatchException(exc.getMessage());
}
EDIT
I saw a post on StackOverflow which briefly mentions why nextLine() after nextInt() is skipped.
i believe this is closer to your intention. this way the reference to your keyboard input that nextLine grabs isn't lost on each iteration, but remains preserved in a new String instance. correct?
System.out.println(i);
String getMe = keyboard.nextLine();
skillAssign[i] = new String(getMe);
System.out.println(skillAssign[i]);

Input validation without using try catch exception

Im writing a program that calculates the investment of a person after a number of years. I prompt the users to enter their name, amount they will be investing, interest rate, and number of years. I'm supposed to do a validation of the input with if...else statements. One of the checks is to see if the user has entered the correct data type. This is for an intro java class. We finished the chapter on methods a week ago, so this is beginner's stuff. I can seem to figure out how to do the data type check. I tried the hasNextInt for my int types but I get an exception which we haven't learned at all. I found some info online on the Pattern and Match classes but there's a lot of stuff in there that we haven't seen yet. Here's one of the methods I wrote to get the correct input.
//Define method for input validation, integer type
public static int getValidInt(String messagePrompt, String messagePrompt2, String messagePrompt3){
Scanner input = new Scanner(System.in);//Create scanner
int returnValue;
int j = 0;
do {//Start validation loop
System.out.printf(messagePrompt); //Print input request
returnValue = input.nextInt();
if (returnValue <= 0) { //Check if user entered a positive number
System.out.println(messagePrompt2);//Print error message
}
else if (!input.hasNextInt()) {
System.out.println(messagePrompt3);//Print error message
}
else {
j++;
}
} while (j == 0);//End validation loop
return returnValue;
}
Im not sure if I have the order of the checks right. Any help is welcome. Thank you.
If it's just 4 pre-defined input fields and you don't have to check for additional things then I don't see a reason to use a do while loop here. Though maybe I don't get what this method is supposed to do, are you returning some kind of integer that defines whether the input was valid or do you actually have to store the values? If the former, why not just return a Boolean or an Enumeration?
I also don't understand why you're simply calling nextInt the first time, but for the next one you are checking whether it has a nextInt.
Also you don't mention what kind of exception you're getting when calling hasNextInt, but apparently this can only be an IllegalStateException. I suggest taking a look at the Java docs at http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html, or reading your relevant course material.
The sequence nextInt() and hasNextInt() is invoked. First one is used to read the value from input, and second is used to see whether the value type is int. So you have to invoke hasNext[Type]() followed by next[Type].
Let's correct those two first as below.
if (scnr.hasNextInt()) {
int userChoice = scnr.nextInt();
} else {
// input is not an int
}
Now let's correct your code to get a valid int.
public static int getValidInt(String messagePrompt, String messagePrompt2, String messagePrompt3) {
Scanner input = new Scanner(System.in);// Create scanner
int returnValue = -1;
boolean incorrectInput = true;
while (incorrectInput) {
System.out.printf(messagePrompt); // Print input request
if (input.hasNextInt()) {
returnValue = input.nextInt();
if (returnValue <= 0) { // Check if user entered a positive number
System.out.println(messagePrompt2);// Print error message
} else {
incorrectInput = false;
}
} else {
input.next();
System.out.println(messagePrompt3);// Print error message
}
}
return returnValue;
}

Categories

Resources