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++){
Related
i've been puzzling over this for about 5 hours now, I just can't get the errors to stop. am I doing something fundamentally wrong, or misunderstanding something? I'm hoping this is fairly simple to some people, as i'm just learning. the point of this program is to calculate taxes and dealership fees on cars using methods and arrays.
package taxesandfeescar;
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author K
*/
public class Taxesandfeescar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int pricesNumber = input.nextInt();
int Prices[] = new int[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + imsg);
Prices[i] = input.nextInt();
}
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("The final price, after taxes and fees of car #" + imsg + " is " + pricesTaxFees[i]);
Prices[i] = input.nextInt();
int pricesTaxFees[i] = applyTaxesAndFees[i];
}
}
public static double[] applyTaxesAndFees(int Prices, int pricesNumber){
int pricesTaxFees[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
pricesTaxFees[i] = Prices[i] / 13 * 100 + 1500;
}
return pricesTaxFees[];
}
}
You have several errors in your code. For example: you dont have to read twice the price of the car. You cannot print the message with the final price before calculating the final price. When you have defined like that applyTaxesAndFees(int Prices, int pricesNumber) you cannot call it like thatapplyTaxesAndFees[i], it is totaly wrong. You shoul call this method like applyTaxesAndFees(Price, priceNumber).
Anyway, check the code above and find and learn from your mistakes like we all do. Have fun with java.
This will work for you.
import java.util.Scanner;
import java.util.Arrays;
/**
*
* #author K
*/
public class Taxesandfeescar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int pricesNumber = input.nextInt();
int Prices[] = new int[pricesNumber];
int pricesTaxFees[] = new int[pricesNumber];
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + imsg);
Prices[i] = input.nextInt();
}
for(int i = 0; i < pricesNumber; i++) {
int imsg = i + 1;
pricesTaxFees[i] = applyTaxesAndFees(Prices[i]);
System.out.println("The final price, after taxes and fees of car #" + imsg + " is " + pricesTaxFees[i]);
}
}
public static int applyTaxesAndFees(int Price){
int pricesTaxFees = 0;
pricesTaxFees = Price / 13 * 100 + 1500;
return pricesTaxFees;
}
}
Here is something working:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many vehicle prices would you like to store?");
int numberOfVehicles = input.nextInt();
double[] vehiclePrices = new double[numberOfVehicles];
for (int i = 0; i < numberOfVehicles; i++) {
int vehicleNumber = i + 1;
System.out.println("Please enter the price, Without taxes or fees, of car #" + vehicleNumber);
vehiclePrices[i] = input.nextInt();
}
for (int i = 0; i < numberOfVehicles; i++) {
int vehicleNumber = i + 1;
vehiclePrices[i] = applyTaxesAndFees(vehiclePrices[i]);
System.out.println("The final price, after taxes and fees of car #" + vehicleNumber + " is " + vehiclePrices[i]);
}
}
public static double applyTaxesAndFees(double pricesBeforeTaxes) {
double priceAfterTaxes = pricesBeforeTaxes + ((pricesBeforeTaxes * 13) / 100) + 1500;
return priceAfterTaxes;
}
my advice would be to check the changes line by line and see the differences. I'm learning as well, but would recommend you to read more about how methods and arrays works. Also - naming conventions are important.
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)]
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
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]);
}
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();