import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();
Related
Say I have 2 Scanner filled arrays, name[] and age[]. Each one filled in order. If I am to find the oldest person in the array how do I print out their name AND their age, using the arrays?
For example the largest entry in age[] was 78. Is there a way to relate it with the name[] array to print it out?.
Reference code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many entries ?");
int entries;
do {
entries = input.nextInt();
if (entries < 1) {
System.out.println("please enter a valid number!");
}
} while (entries < 1);
String[] name = new String[entries];
String[] gender = new String[entries];
int[] age = new int[entries];
for (int i = 0; i < entries; i++) {
System.out.println("Enter the name of person No" + (i + 1) + ".");
name[i] = input.next();
}
double ageSum = 0;
int max = 0;
for (int i = 0; i < entries; i++) {
System.out.println("How old is " + name[i] + " ?");
age[i] = input.nextInt();
ageSum += age[i];
max = Math.max(max, age[i]);
}
System.out.println("the oldest person is "
+ name[] + " whose " + max + " years old.");
}
Assuming that your arrays have the same size and the ages corresponding to the names then you can check for the highest age and store the indice of the element with the highest age.
Then you have your name at this indice.
int highestAgeIndice = 3; //indice of element with age 97 as example
names[highestAgeIndice] // the corresponding name
Calculating highest age and store its indice
int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
if (age[i] > max) {
max = age[i];
highestInd = i;
}
}
System.out.println("the oldest person is " +
name[highestInd] + " whose " + max + " years old.");
The Code
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many entries ?");
int entries;
do {
entries = input.nextInt();
if (entries < 1) {
System.out.println("please enter a valid number!");
}
} while (entries < 1);
String[] name = new String[entries];
String[] gender = new String[entries];
int[] age = new int[entries];
for (int i = 0; i < entries; i++) {
System.out.println("Enter the name of person No" + (i + 1) + ".");
name[i] = input.next();
}
double ageSum = 0;
for (int i = 0; i < entries; i++) {
System.out.println("How old is " + name[i] + " ?");
age[i] = input.nextInt();
ageSum += age[i];
}
int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
if (age[i] > max) {
max = age[i];
highestInd = i;
}
}
System.out.println("the oldest person is " +
name[highestInd] + " whose " + max + " years old.");
}
If you have two arrays name[] and age[], you can relate them by creating some class Person with fields of type the entries in these arrays, and get a list of persons List<Person>, something like this:
static class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
#Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public static void main(String[] args) {
String[] name = {"Junior", "Senior", "Middle"};
int[] age = {25, 78, 40};
List<Person> people = IntStream.range(0, name.length)
.mapToObj(i -> new Person(name[i], age[i]))
.collect(Collectors.toList());
// sort by age in reverse order
people.sort(Comparator.comparing(
Person::getAge, Comparator.reverseOrder()));
// output
people.forEach(System.out::println);
}
Output:
Person{name='Senior', age=78}
Person{name='Middle', age=40}
Person{name='Junior', age=25}
See also: How do I sort two arrays in relation to each other?
You could use indexOf on you array age for the Max age which will tell you the index of the associated name.
names[age.indexOf(Max)]
Here's my code.I'm not yet familliar with lambda expressions in java 8.
I'd like to apply a lambda expression here doing a random generation of healthy and unhealthy horses.
Then I'll print and run only the healthy horses. How can I do that?
import java.util.Scanner;
import java.util.Random;
public class HorseRace {
static int numHorse = 0;
static int healthyHorse = 0;
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
Horse[] horseArray = new Horse[numHorse];
while (counter < horseArray.length) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
horseArray[counter] = new Horse(warCry);
horseArray[counter].setName(horseName);
System.out.println(horseArray[counter]);
System.out.println(this);
System.out.println(healthyHorse);
//unhealthyHorse++;
}
counter++;
}
System.out.println(horseArray.length);
System.out.println("...Barn to Gate...");
for (int i = 0; i < healthyHorse; i++) {
horseArray[i].start();
}
}
}
I have refactored some of the code and used Lambda expressions wherever possible.
public class HorseRace {
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
int numHorse;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
List<Horse> horses = new ArrayList<>();
while (counter < numHorse) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
Horse horse = new Horse(warCry);
horse.setName(horseName);
horses.add(horse);
}
counter++;
}
horses.forEach(horse -> {
System.out.println(horse);
System.out.println(0);
});
System.out.println(horses.size());
System.out.println("...Barn to Gate...");
horses.forEach(Horse::start);
}
}
Lambda expression is used as below:
Input and storing Strings in multi-dimensional arrays with user-input
i have learned multidimensional array from google, it was easy to learn but when i have to implement in any scenerio! its difficult to handle it. i have declared multi-dimensional array using user input and now i want to declare this array in table . how?
import java.util.Scanner;
public class RugbyProject{
final static int RESULT_POINTS_WIN = 2;
final static int RESULT_POINTS_DRAW = 1;
final static int RESULT_POINTS_LOSS = 0;
final static int GAME_POINTS_TRY = 5;
final static int GAME_POINTS_PENALTY = 3;
final static int GAME_POINTS_DROP_GOAL = 3;
final static int GAME_POINTS_CONVERSATION = 2;
public class Stats {
// TODO Auto-generated method stub
int wins;
int draws;
int losses;
int tries;
int penalties;
int dropgoals;
int conversation;
int totalResultPoints = (wins * RESULT_POINTS_WIN) + (draws * RESULT_POINTS_DRAW) + (losses + RESULT_POINTS_LOSS) + (tries * GAME_POINTS_TRY) +
(penalties * GAME_POINTS_PENALTY) + (dropgoals * GAME_POINTS_DROP_GOAL) + (conversation * GAME_POINTS_CONVERSATION) ;
int averageScorePerMatch = (totalResultPoints/5);
}
public static void main(String args[]){
String teams[] = {"Ireland","England","Scotland","Brazil","Irelan","Romania","Germany"};
System.out.println("Welcome to the six nation ChampionShip");
for(String element : teams){
System.out.println("Enter number of wins, draws and losses for " + element);
Scanner myScanner = new Scanner(System.in);
int [] integer = new int[3];
for(int i = 0; i<3; i++){
integer[i] = myScanner.nextInt();
}
System.out.println("ENter total try count, total penalty count ," + " total dropgoal count total conversation count for " + element);
Scanner myScanner2= new Scanner(System.in);
int[] integers2 = new int[3];
for(int i=0; i<3; i++){
integers2[i] = myScanner2.nextInt();
}
}
}
}
So far, I'm just trying to get the input and store it.I am new in java so i am not good in programming
Thats the answer to print array in table
public static void main(String args[]){
String teams[] = {"Ireland","England"};
int [] integer ={};
int[] integers2 ={};
int a=0; int b=3;
System.out.println("Welcome to the six nation ChampionShip");
integer = new int[6];
integers2 = new int[6];
Scanner myScanner = new Scanner(System.in);
for(String element : teams){
System.out.println("Enter number of wins, draws and losses for " + element);
//Scanner myScanner = new Scanner(System.in);
System.out.println("a="+a +" b="+b);
for(int i = a; i<b; i++){
integer[i] = myScanner.nextInt();
}
System.out.println("ENter total try count, total penalty count ," + " total dropgoal count total conversation count for " + element);
//Scanner myScanner2= new Scanner(System.in);
for(int i=a; i<b; i++){
integers2[i] = myScanner.nextInt();
}
a=3;
b=6;
}
System.out.println("Team \tP \tW \tD \tL \t");
for(int j=0; j<teams.length; j++){
//
if(j==0){
System.out.println(teams[j]+"\t"+(integer[j]+integer[j+1]+integer[j+2])+"\t"+integer[j]+"\t"+integer[j+1]+"\t"+integer[j+2]);
}else{
System.out.println(teams[j]+"\t"+(integer[j+2]+integer[j+3]+integer[j+4])+"\t"+integer[j+2]+"\t"+integer[j+3]+"\t"+integer[j+4]);
}
}
I am new to java programming. I am trying to convert an string variable with array to an int variable array
but i have 2 errors and have no idea to fix it,
any help would be great, thanks..
This is my source code :
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int sum=0;
for(x=0;x<=1;x++)
{
System.out.print("input number : ");number[x]=in.next();
int value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum+number[x];
}
for(x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
This is what the errors look like
when you convert an array of stirngs to an array of integers,
we should have an array of integers declared
and in the code that you posted there are some syntax errors because you didnt declare integer array before use(int value[x])
and try the below code which will convert string array of numbers(string number[]) into an ineger array of numbers(int value[])
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100]; // here I declared an array of integers with the name value
int sum=0;
for(int x= 0;x <= 1; x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum + value[x];
}
for(int x=0; x<=1; x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
Use in.nextInt() method.
Scanner in = new Scanner(System.in);
int number[] = new int[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {`enter code here`
System.out.print("input number : ");
number[x] = in.nextInt();
sum = sum + number[x];
}
System.out.println("Sum :\t " + sum);
in.close();
}
Create a int array, then use it. int value[x]= Integer.parseInt(number[x]); is an error because your are trying to assign an integer to an array.
Correct one may be...
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100];
int sum=0;
for(int x=0;x<=1;x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]);
sum=sum+value[x];
}
for(int x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
There seems problem with declaration and usage of variable in you sample code.
Variable x is not initialzed
An integer value is assigned to and array declaration.
Try the below code to solve your issues.
import java.util.Scanner;
public class stringtoint {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {
System.out.print("input number : ");
number[x] = in.next();
int value = Integer.parseInt(number[x]);
sum = sum + value;
}
for (int x = 0; x <= 1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
in.close();
}
}
public static void main(String args[]) {
String[] exampleOfStringArray = {"11", "22", "33"/*, "ab", "cd", "ef", "", null*/};
int[] intArray = getIntArray(exampleOfStringArray);
int sum = getSumOf(exampleOfStringArray);
}
private static int[] getIntArray(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).toArray();
}
private static int getSumOf(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).sum();
}
Try below code, it is working.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
int noOfInputs = 2;
int value[] = new int[noOfInputs];
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.print("input number : ");
number[x] = in.next();
value[x] = Integer.parseInt(number[x]);
sum = sum + value[x];
}
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
}
import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
static int rank[];
int students;
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Please input number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Name?");
name[i] = sc.next();
System.out.println("Korean Score :");
korean[i] = sc.nextInt();
System.out.println("Math Score :");
math[i] = sc.nextInt();
System.out.println("English Score :");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3;
}
}
}
class DataOutput extends DataInput {
public void ranker() {
for (int i = 0; i < students; i++){
rank[i] = 1;
}
for (int i = 0; i < students; i++) {
for (int j = i + 1; j < students; j++) {
if (sum[i] < sum[j]) {
rank[i] += 1;
} else if(sum[i]>sum[j]){
rank[j] += 1;
}
}
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
DataOutput out = new DataOutput();
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean Math English\tSum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.students; i++) {
System.out
.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rank[i]);
}
}
}
So, this is a little program I built. I think the logic is quite right, but when I run the program and type in all the variables, the ranks of students are all 0.
I can't figure out what's the problem. It would be really thankful if someone helps me.
Instead of average[i] = sum[i] / 3; - which does integer math; I think you really need average[i] = sum[i] / 3.0; which should give you a non-zero result.
When you call instantiate a new instance of Data output
DataOutput out = new DataOutput();
it creates all new data. setting the number of students to zero.
Not Recommended
you should either pass in the number of students EDIT and other data
DataOutput out = new DataOutput(students, otherData);
//In Class Constructor
DataOutput(int student, int ... otherData)
{
this.student = student;
for(int i : otherData)
//code
}
Recommended
or you should put the ranker method inside of the dataInput class
class DataInput
{
//code
public int ranker()
{
//code
}
}
The data varible and out variable are "not linked". You call ranker on an "empty" class. Just because DataOutput extends DataInput doesn't mean those two instances are linked/related in anyway.
In the context of the code given: Move the ranker method into the DataInput class and just omit the DataOutput class. Then call ranker() on your data variable.
Use the same derived class object to hold the data on only one object. You are creating two objects.
With DataInput object, data is stored. When you create object for DataOutput, it is fresh object with all default values '0' in all arrays. So use the derived class object for both data storage and output.
out.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean Math English\tSum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < out.students; i++) {
System.out
.println(out.name[i] + "\t\t" + out.korean[i] + " "
+ out.math[i] + " " + out.english[i] + "\t"
+ out.sum[i] + " " + out.average[i] + " "
+ out.rank[i]);
}