Having trouble getting my program to output the index[1] of my array "nArray", if nArray[0] = bob, and nArray[1] = jim. When I'm trying to print the input, it will print nArray[0] bob, but when it gets to nArray[1] it does not output.
public String toString(){
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
public static double salePercent(double[] sArray, String[] nArray){
double total = 0;
for (int b =0 ; b < sArray.length; b++){ // sum calculator
total = total + sArray[b];
}
double percent = 0;
for (int k = 0; k < nArray.length; k++){
System.out.println(nArray[k]);
}
return total;
}
edit
showing how i am creating and declaring and creating my arrays
in my mainclass
System.out.println("How Many Employees :");
int size = input.nextInt();
input.nextLine(); //dummy
String[] nArray = new String[size]; // array for staff names
double[] sArray = new double[size]; // array for staff sales
for (int i = 0 ; i < size; i++){
sales.nameArray(nArray,i, input);
input.nextLine();
sales.saleArray(sArray,i,input);
}
sales.salePercent(sArray, nArray);
in my class
public String inputStaff(){
Scanner user = new Scanner(System.in);
int size;
System.out.print("How Many Employees :\n");
size = user.nextInt();
user.nextLine(); //dummy to grab \n value from nextInt so nextline can function
String[] nArray =new String[size];
double[] dArray = new double[size];
int i =0;
for(i = 0 ; i < nArray.length;i++){
System.out.print("Enter name: ");
nArray[i] = user.nextLine();
System.out.print("Enter sales ($): ");
dArray[i] = user.nextDouble();
user.nextLine();
}
return null;
}
public static String[] nameArray(String[] nArray,int i,Scanner input){
System.out.print("Enter name: ");
nArray[i] = input.nextLine();
return nArray;
}
public static double[] saleArray(double[] sArray,int i,Scanner input){
System.out.print("Enter sales ($): ");
sArray[i] = input.nextDouble();
return sArray;
}
Related
I want all my array data from this class to be passed to another class and I don't know how to do it.
Here is my code:
public static void main(String[] args) {
String menu[] = {"", "Hotsilog", "Porksilog",
"Bangsilog", "Tapsilog", "Chicksilog"};
double priceList[] = {0, 20.00, 20.00, 20.00, 20.00, 20.00};
int quantOrder[] = new int[100];
int foodChoice[] = new int[100];
int qntty = 0;
Scanner scan = new Scanner(System.in);
System.out.printf(" %3s%14s\n", "Menu", "Price");
for (int i = 1; i <= 5; i++) {
System.out.printf("[%d] %-15s%.2f\n", i, menu[i], priceList[i]);
}
System.out.print("How many items do you want to order? ");
qntty = scan.nextInt();
for (int i = 1; i <= qntty; i++) {
System.out.println("Enter the number of your choice: ");
foodChoice[i] = scan.nextInt();
System.out.println("You choose " + menu[foodChoice[i]] + "!");
System.out.print("Quantity of order :");
quantOrder[i] = scan.nextInt();
}
}
And I want all the datas from up there to be passed to this class and compute all the prices
public class methOds {
double Price[] = new double[100];
double totalPrice = 0;
methOds() {
Price[i] = priceList[foodChoice[i]] * quantOrder[i];
totalPrice = totalPrice + Price[i];
}
}
Can some explain me how to work with it?
Thanks in advance!
You need to initialize the pricelist and quantity ordered arrays to the method class and that you can pass into the constructor.
public static void main(String[] args) {
String menu[] = {"", "Hotsilog", "Porksilog",
"Bangsilog", "Tapsilog", "Chicksilog"};
double priceList[] = {0, 20.00, 20.00, 20.00, 20.00, 20.00};
int quantOrder[] = new int[100];
int foodChoice[] = new int[100];
int qntty = 0;
Scanner scan = new Scanner(System.in);
System.out.printf(" %3s%14s\n", "Menu", "Price");
for (int i = 1; i <= 5; i++) {
System.out.printf("[%d] %-15s%.2f\n", i, menu[i], priceList[i]);
}
System.out.print("How many items do you want to order? ");
qntty = scan.nextInt();
for (int i = 1; i <= qntty; i++) {
System.out.println("Enter the number of your choice: ");
foodChoice[i] = scan.nextInt();
System.out.println("You choose " + menu[foodChoice[i]] + "!");
System.out.print("Quantity of order :");
quantOrder[i] = scan.nextInt();
}
methOds method_obj = new methOds(priceList, quantOrder);
System.out.println(method_obj.totalPrice());
}
Modify your constructor and make it a parametrized one by passing both the quantOrder and foodChoice arrays so that the values could be calculated in the
totalPrice method.
public class methOds {
private double Price[] = new double[100];
private double totalPrice = 0;
private int quantOrder[];
private int foodChoice[];
public methOds(quantOrder, foodChoice) {
this.quantOrder = quantOrder;
this.foodChoice = foodChoice;
}
public int totalPrice() {
//Method to calculate the total price
for (int i; i < Price.length; i++) {
Price[i] = priceList[foodChoice[i]] * quantOrder[i];
totalPrice = totalPrice + Price[i];
}
return totalPrice;
}
}
For my university lab work we have to finish 4 tasks. I'm currently on 6 of 9 and have for the most part completed it, but I'm having difficulty in completing the final parts of it. This is the description of what we must do:
Write a program that defines two arrays - one of strings and one of integers, both of size 10.
Your program should then ask the user to enter the a string representing a persons name,
and an integer representing their age. It should continue to do this until either the user
enters ‘done’ instead of a name, or until the array is full (that is, 10 pairs of names and ages
have been entered). It should then print out the names and ages as well as the names of the
youngest and oldest.
Hint: One tricky part is making sure that once you’ve typed ‘done’ to Finish entering names,
your program does not then ask you for the age of the person with name ‘done’ - be careful
about this.
I've highlighted the issues I'm having above in bolded text. Below is the code I currently have, but I'm not sure how to properly accomplish the bolded text.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class nameAge {
public static void main(String[] args){
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
System.out.println("Please enter the name of a person and then their age. Do this for up to 10 people and once finished, type 'done'");
name[0] = in.nextLine();
System.out.println(AGE_REQUEST);
age[0] = in.nextInt();
System.out.println(NAME_REQUEST);
name[1] = in.next();
System.out.println(AGE_REQUEST);
age[1] = in.nextInt();
System.out.println(NAME_REQUEST);
name[2] = in.next();
System.out.println(AGE_REQUEST);
age[2] = in.nextInt();
System.out.println(NAME_REQUEST);
name[3] = in.next();
System.out.println(AGE_REQUEST);
age[3] = in.nextInt();
System.out.println(NAME_REQUEST);
name[4] = in.next();
System.out.println(AGE_REQUEST);
age[4] = in.nextInt();
System.out.println(NAME_REQUEST);
name[5] = in.next();
System.out.println(AGE_REQUEST);
age[5] = in.nextInt();
System.out.println(NAME_REQUEST);
name[6] = in.next();
System.out.println(AGE_REQUEST);
age[6] = in.nextInt();
System.out.println(NAME_REQUEST);
name[7] = in.next();
System.out.println(AGE_REQUEST);
age[7] = in.nextInt();
System.out.println(NAME_REQUEST);
name[8] = in.next();
System.out.println(AGE_REQUEST);
age[8] = in.nextInt();
System.out.println(NAME_REQUEST);
name[9]= in.next();
System.out.println(AGE_REQUEST);
age[9] = in.nextInt();
System.out.println(NAME_REQUEST);
int size = name.length;
int sizeN = age.length;
for (int i=0; i < size; i++) {
System.out.println("Name: " + name[i]);
System.out.println("Age: " + age[i]);
}
int smallest = age[0];
int largetst = age[0];
for(int i=1; i< age.length; i++)
{
if(age[i] > largetst)
largetst = age[i];
else if (age[i] < smallest)
smallest = age[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
}
}
You have to take a look on loop doc in java
this code may help you
public static void main(String[] args) {
int youngest =0,older=0;
String[] name = new String[10];
int[] age = new int[10];
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
for(int i=0 ; i< 10;i++){
Scanner in = new Scanner(System.in);
System.out.println(NAME_REQUEST);
String tmpName = in.nextLine();
if(tmpName.equalsIgnoreCase("done"))
break;
name[i] = tmpName;
System.out.println(AGE_REQUEST);
age[i] = in.nextInt();
if(age[i] > age[older])
older = i;
if(age[i] < age[youngest])
youngest = i;
}
System.out.println("OLDER is : " + name[older]);
System.out.println("Younger : " + name[youngest]);
}
Try this out, I have tested it and it's working fine. Hope that helps. Happy coding.
package com.pearson.nextgen.aggregatedsessionservice;
import java.util.Scanner;
public class NameAgeTest {
public static void main(String[] args) {
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = "Please enter name";
String AGE_REQUEST = "Please enter age";
int count = 0;
while (count < 10) {
System.out.println(NAME_REQUEST);
String nameInput = in.next();
if (nameInput.equalsIgnoreCase("done")) {
break;
}
name[count] = nameInput;
System.out.println(AGE_REQUEST);
age[count] = in.nextInt();
count++;
}
int[] minAndMaxIndex = findMinAndMaxIndex(age, count);
System.out.println("Youngest Person: " + name[minAndMaxIndex[0]]);
System.out.println("Oldest Person: " + name[minAndMaxIndex[1]]);
}
private static int[] findMinAndMaxIndex(int[] inputArray, int count) {
int min, max = 0;
int minIndex = 0, maxIndex = 0;
max = min = inputArray[0];
for (int i = 0; i < count; i++) {
if (inputArray[i] > max)
maxIndex = i;
else if (inputArray[i] < min)
minIndex = i;
}
return new int[] { minIndex, maxIndex };
}
}
I have to make a program where you ask user to enter any number of students, that asks the name and grade of each student. So if I said 2 students, I would put billy smith, then 54, then it would ask me the name of the 2nd student, john smith, then the grade, 81. Then it outputs the names with grades in descending order of grades. It would output:
name---------grades
------------------
John smith 81
billy smith 54
I have evrything except for it printing it out. I need it to print out the name with the grade. Here is what I have:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
Double[] array = new Double[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] =input.next();
System.out.print("Enter the student's score: ");
array[i] = (Double) input.nextDouble();
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
selectionSort(names, array);
System.out.println(Arrays.toString(names));
}
public static void selectionSort(String[] names, Double[] array) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
Double currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
}
}
This is very similar to value base sorted map. The below provided solution would be helpful.
Sort a Map<Key, Value> by values (Java)
This is one way to do it, create a Student class to store name/grade pairs, and use Arrays.sort() with a custom Comparator to sort in descending order after all the input is read:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
//String[] names = new String[numofstudents]; //not needed
//Double[] array = new Double[numofstudents]; //not needed
Student[] students = new Student[numofstudents]; //added
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
//names[i] =input.next();
String student = input.next(); //added
System.out.print("Enter the student's score: ");
//array[i] = (Double) input.nextDouble();
Double grade = (Double) input.nextDouble(); //added
students[i] = new Student(student, grade); //added
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
//selectionSort(names, array);
Arrays.sort(students, new Comparator<Student>() {
#Override
public int compare(Student entry1, Student entry2) {
return entry2.grade.compareTo(entry1.grade); //sort by grade in descending order
}
});
//System.out.println(Arrays.toString(students));
for (int i = 0; i < students.length; i++){
System.out.println(students[i].student + "\t" + students[i].grade);
}
}
}
public class Student{
public String student;
public Double grade;
public Student(String s, Double g){
this.student = s;
this.grade = g;
}
}
/*
* (Sort students) Write a program that prompts the user to enter the number of students,
*the students’ names, and their scores, and prints student names in decreasing
*order of their scores.
*/
package homework6_17;
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student: ");
names[i] = input.nextLine();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student: ");
scores[i] = input.nextDouble();
}
String temps = "";
double temp = 0;
double max = scores[0];
for(int i = 0; i<(scores.length-1); i++){
if(scores[i+1]>scores[i]){
temp=scores[i+1];
scores[i]=scores[i+1];
scores[i+1]=scores[i];
temps = names[i+1];
names[i]=names[i+1];
names[i+1]=names[i];
}
}
for(int i = 0 ; i<(scores.length-1); i++)
System.out.println(names[i]+ " " + scores[i]);
}
}
When i run this program;
run:
Enter number of students: 3
Enter the name of student:
Enter the name of student:
a
Enter the name of student:
b
Enter the score of student:
c
Exception in thread "main" java.util.InputMismatchException
// i got " Enter the name of student: " twice times instead of one.
The first thing that comes to mind (not sure if it is correct here) is that you type the number of students and press "enter". It reads the first int (the 3) and reads the "enter" as the first input for the first student.
Maybe try int numberOfStudents = Integer.ParseInt(input.nextLine());?
That way the newline wont be added to the students.
You just have to remove the first System.out.print("Enter number of students: "); as you are printing the phrase in your for loop for every student. Therefore you are printing it twice for the first student (one time before your loop and one time in your loop)
It's not a good idea to answer homework question in SO. But since you have tried some code, It's OK to answer the Q. Take a look:
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student #" + (i + 1) + ":");
names[i] = input.next();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student " + names[i] + ":");
scores[i] = input.nextDouble();
}
String tempName;
double tempScore;
for (int i = 0; i < numberOfStudents; i++) {
for (int k = i + 1; k < numberOfStudents; k++) {
if (scores[k] > scores[i]) {
tempName = names[i];
tempScore = scores[i];
names[i] = names[k];
scores[i] = scores[k];
names[k] = tempName;
scores[k] = tempScore;
}
}
}
for (int i = 0; i < numberOfStudents; i++)
System.out.println(names[i] + " " + scores[i]);
}
}
I need to make a program that adds long integers without using the biginteger class.
I am working on the add method now and I think I have it correct but I am stuck on returning the correct data type for my method and I'm not sure how to correct it.
Here are my 2 classes so far:
Main Class:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
LargeInteger.class:
public class LargeInteger
{
private int[] intArray;
//convert the strings to array
public LargeInteger(String s)
{
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++)
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
//display the strings
public String display()
{
String result="";
for (int i = 0; i < intArray.length; i++)
result += intArray[i];
return result.toString();
}
//get first array
public int[] getIntArray()
{
return intArray;
}
public LargeInteger add(LargeInteger secondInt)
{
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++)
{
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
return resultArray;
}
}
You need a second LargeInteger constructor:
public LargeInteger( int[] array ) {
intArray = array
}
Then your method can return:
return new LargeInteger( resultArray );
Well first thing, your method add in LargeInteger is supposed to return a LargeInteger, but instead returns an array (int[]). You could fix this by adding a constructor for LargeInteger that takes in an int[] parameter (i.e. LargeInteger(int[] digitArray)). Then, in your add method you could simply do: return new LargeInteger(resultArray);.