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]);
}
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)]
I'm pretty new to coding so please bear with me, I am just experimenting with ways to shuffle an array for eventual use in shuffling a deck of cards in a card game I am creating in Java. I know that index 5 is out of bounds for length 5 but what is puzzling to me is that the error doesn't ALWAYS pop up. Sometimes I try to run my code and it works just fine, other times I get the error even if I haven't changed anything between times that I run it.
public class Card{
public static void shuffle(Object[] array) {
int noOfCards = array.length;
for (int i = 0; i < noOfCards; i++) {
int s = i + (int)(Math.random() * (noOfCards - 1));
Object temp = array[s]; //this is the first line it says has a problem
array[s] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
String[] strOfCards = {"A","B","C","D","E"};
Card.shuffle(strOfCards); //this is the second line that has a problem
for(int i = 0; i < strOfCards.length; i++) {
System.out.println(strOfCards[i] + " ");
}
}
}
I have no idea how to change the flawed lines, any suggestions are welcome!
*** i have tried changing the number of letters in the string but then the error changes with it i.e. "Index 6 out of bounds for length 6"
Consider the lines:
for (int i = 0; i < noOfCards; i++) {
int s = i + (int)(Math.random() * (noOfCards - 1));
Object temp = array[s]; //this is the first line it says has a problem
i varies from 0 to noOfCards - 1
Your random number expression varies from 0 to noOfCards - 2
So s varies from 0 to (2 * noOfCards) - 3
Then array[s] will throw an exception whenever s >= noOfCards
It doesn't happen every time you run it because sometimes the random numbers all happen to be under noOfCards
If you want to swap with a random other card then you could try:
Random random = new Random();
int s = (i + random.nextInt(noOfCards - 1)) % noOfCards;
I realise you're using this as a learning opportunity, but in case you weren't aware, there is a Collections.shuffle method that can be used to shuffle collections such as ArrayList in one command.
Max index of array with length N is (N-1). Code should be like this:
public static void shuffle(Object[] array) {
int noOfCards = array.length;
Random random = new Random();
for (int i = 0; i < noOfCards; i++) {
int s = random.nextInt(noOfCards);
Object temp = array[s];
array[s] = array[i];
array[i] = temp;
}
}
Here is the line that causes the trouble:
int s = i + (int)(Math.random() * (noOfCards - 1));
Whenever the value s is >= 5, the array[s] will point to something out of bound.
For example i can be 3, if Math.random() returns something like 0.5, then 3 + (int)(0.5 * 4) is equal to 5, which is out of bound (0..4)
It doesn't happen all the times, because some times the Math.random() generates small enough number, so the evaluation of s is smaller than 5.
To ensure that the value of s always in the range (0..4), you should modulo the result to 5.
Here is how the line should be:
int s = (i + (int)(Math.random() * (noOfCards - 1))) % 5;
change this line
int s = i + (int)(Math.random() * (noOfCards - 1));
to this
int s = (int)(Math.random() * (noOfCards - 1));
just remove i variable from the above code
You need to remember that indices are zero-based in Java.
Note a couple of things:
- make things final if they're final
- use SecureRandom: it is more random than Random
- use the nextInt(n) method of SecureRandom to get an int in your range
- note the use of Streams to print out the result
import java.security.SecureRandom;
import java.util.stream.Stream;
public class Card {
public static void shuffle(final Object[] array) {
final SecureRandom random = new SecureRandom();
final int noOfCards = array.length;
for (int i = 0; i < noOfCards; i++) {
final int s = random.nextInt(noOfCards);
final Object temp = array[s];
array[s] = array[i];
array[i] = temp;
}
}
public static void main(final String[] args) throws Exception {
final String[] strOfCards = {"A","B","C","D","E"};
Card.shuffle(strOfCards);
Stream.of(strOfCards).forEach(System.out::println);
}
}
If you fancy using a List it's a bit more compact:
import java.security.SecureRandom;
import java.util.*;
import java.util.stream.IntStream;
public class Card {
public static void main(final String[] args) throws Exception {
final SecureRandom random = new SecureRandom();
final List<String> cards = Arrays.asList("A", "B", "C", "D", "E");
IntStream.range(0, cards.size()).forEach(i ->
Collections.swap(cards, i, random.nextInt(cards.size()))
);
cards.forEach(System.out::println);
}
}
M getting the same issue with this code and still no idea how to solve it
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Main
{
public static void main (String[] args)
{
while (true)
{
String number = JOptionPane.showInputDialog("Please Enter \n"
+ "1 for 'Add new Employee'"
+ "\n 2 for 'Search in employee'"
+ "\n 3 for 'Exit'");
int convertnumber = Integer.parseInt(number);
if (convertnumber == 1)
{
addEmployee();
}
else if (convertnumber == 2)
{
String eId = JOptionPane.showInputDialog("Enter ID to search");
searchEmplye(eId);
}
else if (convertnumber == 3)
{
JOptionPane.showMessageDialog(null, "Developed By: BC180401942 SHEHZAD ADEEL");
System.exit(0);
}
else
{
JOptionPane.showMessageDialog(null, "Invalid input");
}
}
}
public static void searchEmplye(String eId)
{
try
{
String tokens[] = null;
String id, name, dob, qual, expe, pays;
FileReader fr = new FileReader("empData.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
if (line == null)
{
JOptionPane.showMessageDialog(null, "Employee Not found");
}
while (line != null)
{
tokens = line.split (",");
id = tokens[0];
name = tokens[1];
dob = tokens[2];
qual = tokens[3];
expe = tokens[4];
pays = tokens[5];
Employee emp = new Employee (id, name, dob, qual, expe, pays);
ArrayList list = new ArrayList();
list.add(emp);
line = br.readLine();
/*
for (int i = 0; i < list.size(); i++)
{
Employee p = (Employee) list.get(i);
if (eId.equals(p.getEmpId()))
{
JOptionPane.showMessageDialog(null, "Employee: \n"
+ "Employee ID: " + p.getEmpId()
+ " \n Employee Name: " +p.getEmpName()
+ " \n Employee DOB: " + p.getEmpDoB()
+ " \n Qualification: " + p.getEmpQualf()
+ " \n Experience: " + p.getEmpExp()
+ " \n Pay Scal: " + p.getEmpPSacle()
);
}
*/
for (int i = 0; i < list.size(); i++)
{
Employee p = (Employee) list.get(i);
if (eId.equals(p.getEmpId()))
{
JOptionPane.showMessageDialog( null, "Employee: \n" +
"EmpId: " + p.getEmpId() + "\n" +
"Name: " + p.getEmpName() + "\n" +
"DoB: " + p.getEmpDoB() + "\n" +
"Qualification: " + p.getEmpQualf() + "\n" +
"Experience: " + p.getEmpExp() + "\n" +
"PayScale: " + p.getEmpPScale() );
}
else
{
JOptionPane.showMessageDialog(null, "Employee Not found");
}
}
}
br.close();
fr.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void addEmployee()
{
try
{
ArrayList list = new ArrayList();
String id = JOptionPane.showInputDialog("Enter Employee ID: ");
String name = JOptionPane.showInputDialog("Enter name: ");
String dob = JOptionPane.showInputDialog("Enter DoB (year): ");
String qual = JOptionPane.showInputDialog("Enter Qualification: ");
String exp = JOptionPane.showInputDialog("Enter Employee experience (in months): ");
String pays = JOptionPane.showInputDialog("Enter Employee Pay Scale (in number): ");
Employee emp = new Employee (id, name, dob, qual, exp, pays);
list.add(emp);
/*
ArrayList list = new ArrayList();
String id = JOptionPane.showInputDialog("Enter ID ");
String name = JOptionPane.showInputDialog("Enter Name ");
String dob = JOptionPane.showInputDialog("Enter DOB ");
String qualification = JOptionPane.showInputDialog("Enter qualification ");
String experience = JOptionPane.showInputDialog("Enter Employee Experience");
String paScale = JOptionPane.showInputDialog("Enter Employee pay scale ");
Employee emp = new Employee(id, name, qualification, experience, paScale);
list.add(emp);
*/
String line;
FileWriter fw = new FileWriter("empData.txt");
PrintWriter pw = new PrintWriter(fw);
for (int i = 0; i < list.size(); i++)
{
emp = (Employee) list.get(i);
//line = emp.getEmpId() + "," + emp.getEmpName() + "," + emp.getEmpDoB() + "," + emp.getEmpQualf() + "," + emp.getEmpExp() + "," + emp.getEmpPSacle();
line = emp.getEmpId() + "," +
emp.getEmpName() + "," +
emp.getEmpDoB() + "," +
emp.getEmpQualf() + "," +
emp.getEmpPScale();
pw.println(line);
}
pw.flush();
pw.close();
fw.close();
}
catch (IOException ioEx)
{
System.out.println(ioEx);
}
}
}
I had to create a java program for my class for a car dealership that sells both new and used cars. We need a program that can ask the user for the number of sales people. Add their names to a String array. Next, ask for sales totals for new cars and used cars separately. Here is my program so far. I was wondering if there was a way to include the following three headers for my table: Name, Used Sales, and New Sales.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numemployees;
System.out.println("Enter the Number of Employees: ");
numemployees = in.nextInt();
String[] names = new String[numemployees];
String line;
for (int i = 0; i < numemployees; i++)
{
System.out.print("Enter the name of the Salesperson: ");
names[i] = in.next();
}
double [][] sales = new double [numemployees][2];
for(int j = 0; j < numemployees; j++)
{
System.out.println("Enter New Car Sales: "+ names[j]);
sales[j][0] = in.nextDouble();
System.out.println("Enter Used Car Sales: ");
sales[j][1] = in.nextDouble();
}
for(int x = 0; x < numemployees; x++)
{
System.out.println(names[x] + "\t" + sales[x][0] + "\t" + sales[x][0] + "\t");
}
}
}
To print header use System.out.println:
System.out.println("Name \t Used Sales \t New Sales");
for(int x = 0; x < numemployees; x++)
{
System.out.println(names[x] + "\t" + sales[x][0] + "\t" + sales[x][1] + "\t");
}
And one more think be careful with indexes: You have used System.out.println(names[x] + "\t" + sales[x][0] + "\t" + sales[x][0] + "\t");. The problem is with sales[x][0] It will only twice print same value.
1I would suggest using String.format for this. Then you get some nice formatting along with it.
System.out.println(String.format("%-10s%-10s%-10s", "Name", "Used Sales", "New Sales"));
for(int x = 0; x < numemployees; x++)
{
System.out.println(String.format("%8.2f%8.2f%8.2f", names[x], sales[x][0], sales[x][1]));
}
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();
package ooptutorial;
public class ShoppingTest {
//name of file must be same as name of method
public static void main(String[] args) {
Shopping firstClient = new Shopping();
int[] pricelist = {299,399,499};
for (int i = 0; i < pricelist.length; i++){
firstClient.Basket(pricelist[i]);
}
System.out.println("The Total Price of your Item is : "
+ firstClient.r);
System.out.println("The Total Price with VAT : "
+ firstClient.TotalPrice());
firstClient.DailyIncome(firstClient.TotalPrice());
Shopping secondClient = new Shopping();
int[] pricelist2 = {599,159,459};
for(int i = 0; pricelist2.length; i++){
secondClient.Basket(pricelist2[i]);
}
System.out.println("The Total Price of your Item is : "
+ secondClient.r);
System.out.println("The Total Price with VAT : "
+ secondClient.TotalPrice());
secondClent.DailyIncome(secondClient.TotalPrice());
System.out.println("The Daily Income : "
+ secondClient._dailyIncome);
}
}
[ed: artificial break added]
class Shopping{
int r = 0;
final int VAT_VALUE = 17;
static int DailyIncome = 0;
int Basket(int ItemPrice){
r = ItemPrice;
return r;
}
int TotalPrice(){
return ((r * VAT_VALUE) / 100) + r;
}
public static int DailyIncome(int income){
_dailyIncome += income;
return _dailyIncome;
}
}
You have an error on this line:
for(int i = 0; pricelist2.length; i++){
Because pricelist2.length is an int, not a boolean as required by Java syntax. Perhaps you meant:
for(int i = 0; i < pricelist2.length; i++){