Is it possible to turn this code into a for loop? - java

I was wondering whether it is possible to turn this code into a for loop. I know that you could loop the text, however, is it possible to do something similar to the variables inputRangeCity1, inputRangeCity2 etc..
System.out.print("Enter maximum cell phone connectivity distance for city 1: ");
double inputRangeCity1 = user_input.nextDouble();
System.out.print("Enter maximum cell phone connectivity distance for city 2: ");
double inputRangeCity2 = user_input.nextDouble();
System.out.print("Enter maximum cell phone connectivity distance for city 3: ");
double inputRangeCity3 = user_input.nextDouble();
System.out.print("Enter maximum cell phone connectivity distance for city 4: ");
double inputRangeCity4 = user_input.nextDouble();

If you declare inputRangeCity1, etc as separate local variables, it is next to impossible to use a loop.
If you declare inputRangeCity1, etc as separate instance (or class) variables, it is possible to use reflection. However, it is not a good solution ... because the code will be more complex, more verbose and fragile.
The best / simplest solution is to use an array rather than separate variables:
double[] inputRangeCities = new double[NOS_CITIES];
and then:
for (int i = 1; i <= inputRangeCities.length; i++) {
System.out.print("Enter maximum cell phone connectivity " +
"distance for city " + i + ": ");
inputRangeCities[i - 1] = user_input.nextDouble();
}
If the number of cities is not known (fixed) at the point where you need to declare the variable, then you should use a List instead. Otherwise, an array is better ... unless there is some other part of the application wthat would benefit from using a list.
If the array / collection approach is not what you need, then consider refactoring like this:
private double readRange(Scanner input, int cityNo) {
System.out.print("Enter maximum cell phone connectivity " +
"distance for city " + i + ": ");
return input.nextDouble();
}
...
double inputRangeCity1 = readRange(user_input, 1);
double inputRangeCity2 = readRange(user_input, 2);
double inputRangeCity3 = readRange(user_input, 3);
double inputRangeCity4 = readRange(user_input, 4);
It is more lines of code ... and I don't like it ... but it is an alternative.

Use a list instead of individual variables.
List<Double> inputRangeCities = new ArrayList<Double>();
for(int i=1; i <= 4; i++)
{
System.out.print("Enter maximum cell phone connectivity distance for city" + i);
inputRangeCities.add(user_input.nextDouble());
}
You can then for example access the value for the first city as inputRangeCities.get(0). Note that the index in a Java list or array always starts at 0.

Related

Why does the code print the statement twice, but differently?

My problem statement is:
Write a program that creates two instances of the generic class
LinkedList.
The first instance is stadiumNames and will hold items of
type String.
The second instance is gameRevenue and will hold items of
type Double.
Within a loop, read data for the ball games played during
a season.
The data for a game consists of a stadium name and the
amount of money made for that game.
Add the game data to stadiumNames and gameRevenue.
Since more than one game could be played at a particular stadium, stadiumNames might have duplicate entries.
After reading the data for all of the games, read a stadium name and display the total amount of money made for all the games at that stadium.
I'm trying to get each input from the user and then add each input together and get its sum, it seems to get it right at first, but then it prints another totally different amount. Why is that? Any help appreciated.
Each input the stadiumName and gameRevenue were added to a linkedList.
Note that I already wrote both linked lists but it won't allow me to post a big chunk of code. Thank you.
boolean Data = true;
while (Data) {
stadiumNames.add(name);
gameRevenue.add(rev);
System.out.println("Do you want another game? ");
String yesorno = scan.next();
if (yesorno.equals("No"))
break;
else {
if (yesorno.equals("yes"))
System.out.println("Enter stadium name: ");
name = scan.next();
System.out.println("Enter amount of money for the game: ");
rev = scan.nextDouble();
for (int i = 0; i < stadiumNames.size(); i++) {
if (stadiumNames.get(i).equals(name)) {
rev += gameRevenue.get(i);
System.out.println("The total amount of money for " + name + " is " + rev);
}
}
}
}
If you want to print running total while user is entering the data, total should be reset for each calculation.
while (true) {
System.out.println("Do you want another game? ");
String yesorno = scan.next();
if (yesorno.equals("No"))
break; // else not needed
System.out.println("Enter stadium name: ");
name = scan.next();
System.out.println("Enter amount of money for the game: ");
rev = scan.nextDouble();
stadiumNames.add(name);
gameRevenue.add(rev);
double total = 0.0;
// recalculating the total for the last stadium
for (int i = 0; i < stadiumNames.size(); i++) {
if (stadiumNames.get(i).equals(name)) {
total += gameRevenue.get(i);
}
}
System.out.println("The total amount of money for " + name + " is " + total);
}
However, it may be needed to calculate the totals for multiple different stadiums and a map needs to be created and filled for this after the while loop.
It is convenient to use Map::merge function to accumulate the totals per stadium name.
Map<String, Double> totals = new LinkedHashMap<>();
for (int i = 0; i < stadiumNames.size(); i++) {
totals.merge(stadiumNames.get(i), gameRevenue.get(i), Double::sum);
}
totals.forEach((stad, sum) -> System.out.println("The total amount of money for " + stad + " is " + sum));
Aside comment: it is not recommended to use double for financial calculations because floating point maths is not precise.

Storing input data

Can anyone help me here?? I have compiled and successfully run a program using Java which takes user inputs from an "inputdialog" box and displays this information back in the console along with a simple mathematical formula. The problem I cannot seem to overcome is when the data is input the user has an option to enter another set of the same data type but I need the console to register this as a second input. This is how far I am currently with the section of code and my ideas on how to make this work using an array but I have been informed that saving/storing the data as an object might be a better option?
private void enterCar()
{
String carInfo;
int carHours;
int i = 0;
int[] carNumb = new int[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
{
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car "+carNumb+" entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf(""+carInfo+" "+carHours+" $");
if (carHours == 1)
System.out.printf("%3.2f",fee*(carHours));
else if (carNum == 2)
System.out.printf("%3.2f",fee+4.50);
else if (carHours >= 3)
System.out.printf("%3.2f",3+(carHours*4.50));
System.out.printf("\n\n");
}
}
When I compile and run the console I get the line "Details for car [I#6659c656 entered". This line does change to something like "[I#7665c575" the next time I activate the option so I can assume that I may need to assign a value to the number differently?
I have tried the option that is show in the code provided as well as trying to activate a list using (1, 2, 3, ect) but this also just outputs that random line of numbers and letters.
I guess to simplify my question. I need to store 20 individual inputs from an 'InputDialog' box and store it for later access in a console.
I need to store 20 individual inputs from an InputDialog box and store it for later access in a console.
Use a loop such as for.
That information then gets stored as "Details for car 1 entered:" and then the information displayed.
As I said before, you should use index of array instead of array. And because array is zero-based index, so I use carNumb[i] + 1 to print out the order.
Then calculate fee and store to carNumb array.
Note that, your fee is double type => carNumb should be double type to store correct value.
Full code:
public void enterCar() {
String carInfo;
int carHours;
int i = 0;
double[] carNumb = new double[20];
double fee = Double.parseDouble("7.50");
double sum = 0;
final int MAX = 12;
for (; i < carNumb.length; i++) {
carInfo = JOptionPane.showInputDialog("Please enter the license plate of the car");
carHours = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of hours the car was parked (1-12):"));
System.out.printf("\n");
System.out.printf("Details for car " + (carNumb[i] + 1) + " entered:\n");
System.out.printf("License plate Hours Fee:\n");
System.out.printf("" + carInfo + " " + carHours + " $");
carNumb[i] = getFee(fee, carHours);
System.out.printf("%3.2f", carNumb[i]);
System.out.printf("\n\n");
}
}
private double getFee(double fee, int hours) {
if (hours == 1) {
return fee;
}
if (hours == 2) {
return fee + 4.5;
}
if (hours >= 3) {
return 3 + hours * 4.5;
}
return 0;
}
Did I get your idea?

JAVA: How to calculate sum of user-inputted numbers in a loop (numbers are stored in same variable)

This code is part of a receipt-program. I looped it so that users can input item prices (20 item maximum). I need to print the sum of all item-prices. Note that all item-prices are stored into the same double variable newItemPrice. Is this even possible? If not, please give me an idea on another way to do this.
while(x < 20){//maximum of 20 items
x++;//item # (x was decalred as an integer of 1)
System.out.println("\nEnter new item's price");
Scanner newItemPriceSC = new Scanner(System.in);
Double newItemPrice = newItemPriceSC.nextDouble();//scans next double (new item's price)
System.out.println("ITEM # " + x + "\t" + "$" + newItemPrice);//item prices
System.out.println("\n");
System.out.println("type \"no more!\" if there are no more items\ntype any other word to continue");
Scanner continueEnd = new Scanner(System.in);
String answ = continueEnd.nextLine();
if(!(answ.equals("no more!"))){
continue;
}
if(answ.equals("no more!")){
break;//ends loop
}
break;//ends loop (first break; was for a loop inside of this loop)
Declare a new variable before your while starts:
double total = 0;
Then add one line of a code in your cycle:
Scanner newItemPriceSC = new Scanner(System.in);//your code
Double newItemPrice = newItemPriceSC.nextDouble();//your code
total +=newItemPrice; //this is the new line
When the cycle will be ended, the "total" variable will contain the sum of all the prices entered.
You can use newItemPrice to accumulate all the prices by just incrementing it with the currently scanned price.
Double newItemPrice += newItemPriceSC.nextDouble();
However, then you lose the ability to print out the price in the next line.
You'll need to introduce a temporary variable with the results of newItemPriceSC.nextDouble() so you can print it out. If you lose the requirement of printing out the item price, then you don't need the temporary value.

I need of assistance with array assigning user inputs to an array, and do-while loop repeat

I'm having a few problems with my code, this is the over all goal of the program.
One of your professors hears of your emerging programming expertise and asks you to write a SINGLE program that can be used to help them with their grading. The professor gives three 50-point exams and a single 100-point final exam. Your program will prompt the user for the student’s name, entered as Firstname Lastname (i.e. Bob Smith), the student’s 3-exam scores and 1-final exam score (all whole numbers). Class size varies from semester to semester, but 100 is the limit (declare as a constant).
Read in information for ALL students before doing any calculations or displaying any output. Verify that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered. Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid, display an error message and allow the user to re-enter that invalid score. Once all student info is read in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade.
This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int [] exams = new int[MAX_STUDENTS * 4];
int student = 1;
do
{
System.out.print("PLease enter the name of student " + student + ": " );
for (int k = 0; k < 1; k++) {
names[k] = s.nextLine().toUpperCase();
}
for ( int i = 0; i < 4; i++){
if(i==3){
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else{
System.out.print("Please enter score for Exam " + (i+1) + ": ");
exams[i] = s.nextInt();
if((exams[0]<MIN_EXAM||exams[0]>MAX_EXAM)||(exams[1]<MIN_EXAM||exams[1]>MAX_EXAM)||(exams[2]<MIN_EXAM||exams[2]>MAX_EXAM)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[3]<MIN_FINAL||exams[3]>MAX_FINAL){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if(again!="y")
student++;
}while (again.equalsIgnoreCase ("y"));
System.out.println("***Class Results***");
System.out.println(names[1] + "," + names[0] + " " + "Exam Percentage: "+ ((exams[0]+exams[1]+exams[2]+exams[3])/(MAX_EXAM*3+MAX_FINAL)));
}
}
The problems i have have are:
figuring out how to assign the user entered test scores beyond just the first student, i believe i have it set up correct for just one, but it runs into a problem when i would move on to the second student.
For some reason that I cannot figure out the line
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
doesn't allow me to enter anything, not y not n not anything, so my program effectively ends there, it doesn't make sense to me because I've done it exactly like that before and it has worked.
other than that, if there are any other problems that you can see with my code pointing them out would be extremely helpful.
Thank you
EDIT-
new problem i am having, after changing to
if(!again.equalsIgnoreCase("y"))
student++;
}while (again.equalsIgnoreCase ("y"));
it lets me type things in now, but after i type in y it prints the next line as
Please enter the name of student 1: Please enter score for Exam 1:
I don't know why or what i need to change to fix it, any suggestions?
`if(again!="y")` is the culprit here
You should use equals() method to check string equality.
if(!again.equals("y"))
If you compare Strings in Java using the == or != operators then you are not actually comparing the values. Instead you are testing if the two Strings are the same Object.
This post explains String comparison well.
To do what you want, change if (again != "y") to if(! (again.equalsIgnoreCase("y")) )
EDIT
I believe your new problem stems from the first for loop you do inside your do loop. Each time you type "y" at the end of your do/while you are going to execute the entire
for (int k = 0; k < 1; k++) {
loop again. This is why after you type "y" you are seeing Please enter the name of student 1: Please enter score for Exam 1:
A "solution" to your new issue would be to make it so the outer for enclosed the inner one, looping through 4 exams for each student usually referred to as a "double for" or "nested for loop".
That said you would then be presented with the issue of having all the exams for ALL students in a single array.
I think now is the time to sit down and put some serious thought into the design of your program. It would be much easier for you if you used a Student object to represent a student and hold their exam scores, IMO. Then you could create an array of Students as opposed to two different arrays you have now.
Here are some "starter" steps (Not necessarily a complete list):
Make a Student class that has variables for the student's first & last name, as well as an array to hold that Students exam scores
In your main class create an ArrayList to hold all of the new Student objects you will be creating.
Do your do/while loop. At the beginning of the loop create a new Student object. Then ask for the Students name and exam scores (note that if you KNOW there will only be the 4 exam scores you don't have to do any extra logic there. You can simply ask for the 4 exam scores using a for loop, or if you want all at one time. if there are a variable number of scores you will have to do some sort of check)
Add the new Student you have created to the ArrayList of Students.
Once the person selects "n", loop through the ArrayList and print the information for each Student!
Your for (int k = 0; k < 1; k++) loop will execute only once (for one student) because you have it set up to execute only while k < 1, which will happen only once. As soon, as you increase k to 1, the loop will stop. I would change it to for (int k = 0; k < MAX_STUDENTS; k++) to make sure it will loop through until you reach the max number of students allowed.

Why is this giving me an infinite loop?

I was going through a code used to calculate investments until it has doubled and I received an infinite loop that I can't seem to solve. Can anyone figure out why this is giving me an infinite loop? I've gone through myself but I can't seem to find the problem. The "period" referred is how many times per year the interest is compounded.
double account = 0; //declares the variables to be used
double base = 0;
double interest = 0;
double rate = 0;
double result = 0;
double times = 0;
int years = 0;
int j;
System.out.println("This is a program that calculates interest.");
Scanner kbReader = new Scanner(System.in); //enters in all data
System.out.print("Enter account balance: ");
account = kbReader.nextDouble();
System.out.print("Enter interest rate (as decimal): ");
rate = kbReader.nextDouble();
System.out.println(" " + "Years to double" + " " + "Ending balance");
base = account;
result = account;
for (j=0; j<3; j++){
System.out.print("Enter period: ");
times = kbReader.nextDouble();
while (account < base*2){
interest = account * rate / times;
account = interest + base;
years++;
}
account = (((int)(account * 100))/100.0);
//results
System.out.print(" " + i + " " + account + "\n");
account = result;
}
The code should ask for three "periods", or three different times the entered data is compounded per year (ex annually, monthly, daily etc.)
Thanks a lot!
Instead of doing
account =interest +base
You should have
account = interest +account
You should add some sanity checking. Either check if all the numbers will result in a finite number of loops (account and rate != 0, maybe some other stuff), or more simply, break if you've looped more times than would be reasonable (say 1000 for instance). My guess is that rate is 0 resulting in no increase in account, therefore it will loop forever.
You have a calculation error:
account = interest + base;
Presumably this should be:
account = account + interest;
Also, are you sure you want to have the int cast?
account = (((int)(account * 100))/100.0);
You're throwing away the values smaller than 1 cent apparently. However, if the interest is too small you will not get any change.
The reason it may loop forever is that the double calculation of account is effectively truncated by casting to int, so it may never change if rate is too small and the new value of account isn't made larger by at least 0.005.

Categories