Reputation: 378
println("This program allows you to enter your exam results!");
int n0 = readInt("How many exam results do you have? ");
for (int n=1; n<=n0; n++) {
String r0 = "r"+n;
int result = readInt("Result "+n+": ");
println(r0);
}
I am new to java and I was wondering if it would be possible for me to set 'String r0' variable's contents as 'int result' variable's name (instead of result).
I wish to do so as my program will have multiple 'int result's and I will need to use each individual one later on for arithmetic purposes.
Upvotes: 0
Views: 760
Reputation: 2199
Below I have A program that will work. I would copy the code and try and rewrite it yourself to make sure you fully understand what is going on.
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
// Initialize Variables
int examCount = 0;
double examSum = 0;
Scanner input = new Scanner(System.in);
// Prompt The user For Number Of Exams And Recieve Value
System.out.print("Number Of Exams? ");
examCount = input.nextInt();
// Create An Array That Is The Length Of The Number Of Exams And Holds Double Values
double[] exams = new double[examCount];
// Read In All Exam Scores. A For Loop Is Used Because You Know How Many Scores There Are
for (int i = 0; i < examCount; i++)
{
System.out.print("Exam Score: ");
exams[i] = input.nextDouble();
}
// Print Out All Of The Scores
for (int i = 0; i < examCount; i++)
System.out.println("Exam #" + (i+1) + "\t" + exams[i]);
// Sum All Of The Exam Scores
for (int i = 0; i < examCount; i++)
examSum += exams[i];
// Print Out An Average Of All Of The Scores
System.out.println("Exam Average: " + examSum / examCount);
}
}
Upvotes: 0
Reputation: 33534
1. First do not declare r0 as String
as you intend to use it as integer
, but declare it as int
, ya offcourse you can convert
string to integer using Integer.parseInt()
.
eg:
String r0 = "10";
int r = Integer.parseInt(r0);
2. I will advice you to use Collection framework for storing of mulitple data in java as it gives great flexibilty. Use ArrayList<Integer>
.
eg:
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int n=1; n<=10; n++) {
arr.add(n);
}
Upvotes: 0
Reputation: 272217
I think what you really need to do is have a collection or array of results. Anytime you think you need something like:
int r0 = ...;
int r1 = ...;
int r2 = ...;
etc. then it's good indication that you're looking at some sort of collection.
So in the above example, you'd build an array of size number of exam results, and then populate each element of the array in turn.
Here's the Java array tutorial. It's also worth looking at the Java collection tutorial, if only to compare/contrast.
Upvotes: 3
Reputation: 793
Even if you could, I don't imagine that would be a very good idea! It would be a nightmare to get to them to refer back to them later on.
In your situation, I would just recommend using an array of int
s for your results instead.
Upvotes: 1