Need help declaring a variable within a for loop (Java) - java

I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.

The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.

Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);

for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}

You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;

Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}

Related

How to calculate input from an array

I'm having trouble with this array I'm working on. In the for loop, I need to somehow calculate an on base percentage. The element at index 0 will store the OBP. How can I retain the information the user inputs to calculate the OBP? Thank you.
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[index] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[index] = keyboard.nextInt();
}
I'd suggest a HashMap inside a HashMap for this use case.
Before loop:
HashMap<Integer, HashMap<String, Integer>> years = new HashMap<>();
HashMap<String, Integer> entry = new HashMap<>();
For every input from user's keyboard (example):
entry.put("hits", 5);
years.put(2019, entry);
entry.put("walks", 10);
years.put(2019, entry);
In the end you get a result such as:
{2019={hits=5, walks=10}}
Retrieving results is simple too:
// retrieve map of data for a specific year:
years.get(2019)
result: {hits=5, walks=10}
// retrieve specific data for a specific year:
years.get(2019).get("hits")
result: 5
You will want to store the values entered by the user in a variable. Instead of having an array of inputs (which is one way of doing it) - you can simply store each value in a separate variable and then do the calculation at the end.
See my sample code below:
public static void main(String args[]) {
// let's take incoming values from the user for our calculations
Scanner keyboard = new Scanner(System.in);
// we'll use this array to store the values entered by the user
// in position zero of the array we'll store the OBP
// in positions 1-5 we'll store the inputs as entered by the uesr
float[] values = new float[6];
// we'll use this flag to determin if we should ask the user input again or quit the program
boolean letsDoThisAgain = true;
while (letsDoThisAgain){
System.out.println("Enter a Year: ");
int year = keyboard.nextInt();
System.out.println("For Year " + year + ", enter number of:");
System.out.println("Hits: ");
values[1] = keyboard.nextFloat();
System.out.println("Walks: ");
values[2] = keyboard.nextFloat();
System.out.println("Number of times player has been hit by a pitch: ");
values[3] = keyboard.nextFloat();
System.out.println("Number of at bats: " );
values[4] = keyboard.nextFloat();
System.out.println("Number of sacrifice flies: ");
values[5] = keyboard.nextFloat();
// calculate the OBP
values[0] = (values[1] + values[2] + values[3] - values[5] ) / values[4]; // or however you calculate it
System.out.println("OBP: " + values[0]);
System.out.println("------");
System.out.println("Do you want to do it again? (y/n): ");
String quitOrDoItAgain = keyboard.next();
if( "n".equalsIgnoreCase(quitOrDoItAgain)){
letsDoThisAgain = false;
}
}
System.out.println("Thanks for playing... Good Bye!");
}
By the usage of a proper data structure like Map<string year, object playerstats> including OBP calculation on the object player stats before storing but this is an in-memory solution only last till the program is running if you like persistent then look on the database side
Also from the way you have presented your code it seems you are over-writing the value at year[index] always.
if you just want to use an array, then go like
years[index] = year[index] (math operation) keyboard.nextInt()

My java arrays overwrite existing elements

So I am relatively new to Java language but am trying to get better so I can add more skills to my resume. I am currently focusing on arrays and I am writing a program that I want to be able to use with a barcode scanner or keyboard in order to keep track of Cultural Enrichment credits (inspired by my school's need of one ). I thought it might be a neat starting program to wrap my head around array use but I am having a problem with the two arrays. They keep overwriting the new values entered. I have been googling and trying things but I am still not able to get them to work properly and would like to ask for help from more seasoned coders. I know my output method is rather lazy but it'll do for what I would like to see for the output format.
Here is my code:
public static void main(String []args)throws InputMismatchException
{
Scanner user_input = new Scanner( System.in );
int n = 0;
String Name;
int CEU;
String[] users = new String[5];
String[] numbers = new String[6];
Object end = null;
Object print = null;
System.out.print("Enter value for CEU: ");
CEU = user_input.nextInt();
while (n >= 0)
{
/* Loop*/
System.out.println("Scan ID or type **end,print** ");
numbers[n] = user_input.next();
if ("end".equals(users[n] ))
{
System.out.print("Program terminated.");
System.exit(0);
}
if ("print".equals(numbers[n]))
{
System.out.print("CEUs: " + CEU);
System.out.print(" ID#: " + numbers[0]);
System.out.print(" Name: " + users[0]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[1]);
System.out.print(" Name: " + users[1]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[2]);
System.out.print(" Name: " + users[2]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[3]);
System.out.print(" Name: " + users[3]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[4]);
System.out.print(" Name: " + users[4]);
}
else
{
System.out.print("Enter Name: ");
users[n] = user_input.next();
}
}
}
Inside your loop you need to increment n as it is always 0. Use: n++; at the last line of code inside the while loop.
n isn't being incremented. Because n never changes, it will override the same part of the array each time the loop executes. Also, it seems like you may get a outofbounds error later, because i will keep increasing. Soon it will be greater than the max index of the numbers array, so it will return the error. You should try adding in some code that stops the error from happening.

Trouble getting my while loop to work

I'm currently working on this assignment for a class and I'm having a hard time getting my while loop to work. Can anyone assist me on figuring out why I can't get the user to enter y or n to either restart the loop or terminate it? Thank you so much!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main (String[] args) {
String another="y";
double percent;
int answers;
int score = 0;
Scanner scan = new Scanner(System.in);
NumberFormat fmt = NumberFormat.getPercentInstance();
// Asks the user to input the amount of questions on the quiz
System.out.print("How many questions are on the quiz? ");
final int QUESTIONS = scan.nextInt();
System.out.println(); // spacer
int[] key = new int [QUESTIONS];
// Asks the user to enter the key
for (int i=0; i<key.length; i++){
System.out.print("Enter the correct answer for question "+ (i+1) +": ");
key[i] = scan.nextInt();
}
System.out.println(); // spacer
while (another.equalsIgnoreCase("y")) {
// Asks the user to enter their answers
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
// Grades the amount of questions right and gives the percentage
percent = (double)score/QUESTIONS;
System.out.println();
System.out.println("Your number of correct answers is: " + score);
System.out.println("Your quiz percentage: " + fmt.format(percent));
System.out.println();
System.out.println("Grade another quiz? (y/n)");
another = scan.nextLine();
}
}
}
So instead of this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
you should try this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
scan.nextLine();
At the end of your while loop, try adding this print statement:
System.out.println("Next line is >>>" + another + "<<<");
That should make it clear what you are getting from the scan.nextLine() call. It won't fix your problem, but it will make the issue obvious.
It has to do with that your scan is reading integers before getting the y/n from the user.
In this transition, the scan is reading a newline character instead of y. As a result, the another is a newline char and hence fails the while-loop condition.
To overcome this, the shortcut method is what #3kings had mentioned.
Another method is scan all inputs as string (nextLine) and then for the quiz part, parse for integer. It may seems a lot of work but you get to use parseInt and try/catch exception.

Listing multiples of user-inputted numbers

The task is to "Write a program that displays a user-indicated number of multiples for an integer entered by the user."
I suppose I do not need a completely direct answer (although I do want to know the methods/formula to use), as I want to use this as a learning experience in order to do and learn from the task myself. I really want to know about the process and which methods to use, along with finding a formula. :||
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
So far, I have:
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
\\just stuff to base my code off of
int integer;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
\\pretty much everything from here on out.. I'm not sure what to really do.
int n = integer;
int result = (integer * (numberMultiples));
while (result > 0){}
System.out.print(result);
}
} \\at the moment this code doesn't seem to have any running errors
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
NEW QUESTION
I need to loop my program as well. (By asking a question to the user first.) Mines isn't working, as it just keeps looping only the integer loop and doesn't let me type yes/no.
import java.util.Scanner;
public class MultipleLoops
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int integer, numberMultiples;
String repeat = "yes";
while (repeat != "no")
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++){
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
}
}
}
Ok so you need to understand the problem first to know how to solve it
x = First input
n = Second input
you need to calculate n multiple of x
example with x = 3 and n = 10
To calculate 10 multiple of 3 we need to do :
1st multiple = x*1
2nd multiple = x*2
3rd multiple = x*3
...
n multiple = x*n
you can notice that these operations can be replaced by one for loop (notice first and last character of every line, it can be index of your loop )
Back to java :)
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
Replace your code with the following and try this code :
import java.util.Scanner;
public class MultipleLooping{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int integer,numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
}
}
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing multiple N# 1 = 3
Listing multiple N# 2 = 6
Listing multiple N# 3 = 9
Listing multiple N# 4 = 12
Listing multiple N# 5 = 15
Listing multiple N# 6 = 18
Listing multiple N# 7 = 21
Do you want like this ? Below is the code
package com.ge.cbm;
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//just stuff to base my code off of
int integer;
int firstEntered;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
firstEntered = integer;
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
//pretty much everything from here on out.. I'm not sure what to really do.
for (int i=0;i<numberMultiples;i++){
integer=integer*firstEntered;
System.out.println(integer);
}
}
}
Output:
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing the first 7 multiples of 3:
9
27
81
243
729
2187
6561
this should work
while(repeat.equals("yes"))
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++)
{
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
repeat = keyboard.nextLine();
}

Trying to restart a do-while loop with a String variable to equal "yes" or "no"

Very simple program calculating travel distance(just started a week ago) and I have this loop working for a true or false question, but I want it to work for a simple "yes" or "no" instead. The String I have assigned for this is answer.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double distance;
double speed;
boolean again = true;
String answer;
do{
System.out.print("Tell me your distance in miles: ");
distance = input.nextDouble();
System.out.print("Tell me your speed in which you will travel: ");
speed = input.nextDouble();
double average = distance / speed;
System.out.print("Your estimated time to your destination will be: " + average + " hours\n\n");
if(average < 1){
average = average * 10;
System.out.println(" or " + average + " hours\n\n");
}
System.out.println("Another? ");
again = input.nextBoolean();
}while(again);
}
}
You need to use input.next() instead of input.nextBoolean(), and compare the result to a string literal "yes" (presumably, in a case-insensitive way). Note that the declaration of again needs to change from boolean to String.
String again = null;
do {
... // Your loop
again = input.nextLine(); // This consumes the \n at the end
} while ("yes".equalsIgnoreCase(again));
just do
answer = input.nextLine();
} while(answer.equals("yes"));
You might want to consider being more flexible though. For example:
while (answer.startsWith("Y") || answer.startsWith("y"));
String answer=null;
do{
//code here
System.out.print("Answer? (yes/no) :: ");
answer=input.next();
}while(answer.equalsIgnoreCase("yes"));
the above condition makes " while" loop run if user enter's yes and will terminate if he enters anything except yes.

Categories