I'm trying to assign a different number to the indexes of my array without modifying the array. for example on my code it prints Salesperson 0, Salesperson 1, etc as it gets the index ID of the array in my code. what i'm trying to achieve is that the information of Salesperson 1 be assigned to the index 0 on my array so that it doesn't display as Salesperson 0 on my output.
here is my code.
import java.util.Scanner;
import java.text.NumberFormat;
public class Sales {
public static void main(String[]args)
{
NumberFormat money = NumberFormat.getCurrencyInstance();
//part where program asks how many persons to compute
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of Salesperson: ");
int SALESPEOPLE = scan.nextInt();
//part where variables are declared
int[] sales = new int[SALESPEOPLE];
int sum;
float ave;
int max_sales=0;
int max_person=0;
int min_sales=0;
int min_person=0;
//part where values for sales are asked and entered
for (int i=0; i<sales.length; i++)
{
System.out.print("Enter sales for salesperson "+i+": ");
sales[i]=scan.nextInt();
//part where sales are compared to find the minimum and maximum sales
if (i == 0)
{
min_sales = sales[i];
max_sales = sales[i];
}
if (sales[i] > max_sales)
{
max_sales = sales[i];
max_person = i;
}
if (sales[i] < min_sales)
{
min_sales=sales[i];
min_person=i;
}
}
System.out.println("\nSalesperson Sales");
System.out.println("----------- --------");
sum=0;
ave=0;
//part where the sales are displayed
for (int i=0; i<sales.length; i++)
{
System.out.println(" "+i+" "+money.format(sales[i]));
sum += sales[i];
ave = sum/SALESPEOPLE;
}
System.out.println("\nTotal sales "+money.format(sum));
System.out.println("Average sales "+money.format(ave));
System.out.println("Salesperson "+min_person+" had the highest sale with "+money.format(min_sales));
System.out.println("Salesperson "+max_person+" had the highest sale with "+money.format(max_sales));
}
}
If I understand correctly, just change what you are printing
System.out.print("Enter sales for salesperson "+(i+1)+": ");
Also, this line
System.out.println(" "+(i+1)+" "+money.format(sales[i]));
Also you duplicate the highest sales string in your output at the end
Other than that, I don't see any problems with your code
You can't change the indexes of an array. But if you want to change the output in a way that you print salesperson0 when you access the 1 index of your array you can just do what Thomas said.
save the array values in another array, swap them
define a rule for the indexes... maybe you could create a function for the array which returns value at index x if you provide index y....
Related
So I'm trying to make a cash register program that takes in an array of integer prices and then adds them together to get the total sale price. Here's the snippet of my code that's important
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
for(int i=0; i<Prices.size(); i++)
{
int Total = Prices.get(i) + Prices.get(i+1);
}
System.out.println(Total);
My error says "Total cannot be resolved to a variable" and earlier it didn't like when i tried to make the increment in the loop i+2 instead of i++. Can someone help I have no idea how to add together these variables
Is this the right track?
for(int i=0; i<Prices.size(); i++)
{
int Total = 0;
int Total = Total + Prices.get(i);
}
No need of an array or list.
int total = 0;
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
total += i;
System.out.println();
}
System.out.println(total);
You're doing 2 things wrong here:
int Total = Prices.get(i) + Prices.get(i+1);
You're declaring Total inside the for loop. Do that outside with a default value of 0. Then you are adding the values of the current iteration and the next iteration. You just want to do Total = Total + Prices.get(i); or Total += Prices.get(i);.
Preferably, you can do it all as you get the values. There's no need for the additional list Prices:
int total = 0;
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
total += i;
//prices.add(i);//if you still want to keep the list
System.out.println();
}
while(in.hasNextInt());
System.out.println(total);
You have declared Total in a different scope than you are trying to use it. Additionally the logic in your loop is flawed for summing the prices. Try this:
int Total = 0;
for(int i=0; i<Prices.size(); i++)
{
Total = Total + Prices.get(i);
}
System.out.println(Total);
The code below works fine for the largest value but for the smallest value it is displaying: smallest number is 0 for any 3 values I input. Would greatly appreciate any help.
import java.util.Scanner;
class MyClass{
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[3];
int smallest = numbers[0], largest = numbers[0];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 3 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
// for loop to find largest and smallest values
for (int i=0 ;i< numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
}
System.out.println("largest number is "+largest);
System.out.println("smallest number is "+smallest);
}
}
Smallest is always initialized as 0 here: int smallest = numbers[0]. Unless the user enters a value smaller than 0, smallest value will stay 0. Use Integer.MAX_VALUE (int smallest = Integer.MAX_VALUE) instead to ensure that the smallest number will actually be selected.
You're initializing smallest to 0, so if none of the numbers in the array are less than 0, you'll still get 0 as the result. Instead initialize it to Integer.MAX_VALUE, which is the highest value the integer datatype can have.
public static void getMaxMin(int a, int b, int c){
int max=a;
int min=a;
if(b>max){
max=b;
}
if(c>max){
max=c;
}
if(b<min){
min=b;
}
if(c<min){
min=c;
}
System.out.println("min="+min);
System.out.println("max="+max);
}
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[3];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 3 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
//Use in built Math.min and Math.max to get smallest and largest numbers
System.out.printf("%s: %d%n", "smallest number is ", Math.min(numbers[0], Math.min(numbers[1], numbers[2])));
System.out.printf("%s: %d%n", "largest number is ", Math.max(numbers[0], Math.max(numbers[1], numbers[2])));
}
}
Beginner Java programmer here. I am trying to make a program that asks the user how many grades they would like to enter. Then, I want to store the grades the user entered into an array. Finally, I want to find the mean of the grades entered and print out a list of every grade below the mean. As of now, my code calculates the mean of the grades that the user enters but I cannot figure out how to print the grades below the mean. I believe the problem lies in my last for loop but I cannot figure out how to fix it. Also, did I implement the array correctly? Thanks to every who took the time to help me!
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
// user enters # of grades they requested to enter
for (int counter = 0; counter < q; counter++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
double[] scores = new double[] {grades};
// adds up all elements (grades)
for (int k = 0; k < scores.length; k++) {
total += scores[k]; //sums up entered grades
}
}
total = total / q; //calcs mean
//loops prints grades less than mean
for (grades = 0; grades < total; grades++){
System.out.println(grades);
}
}
public static void grades(){
Scanner in = new Scanner(System.in);
System.out.println("How many grades would you like to enter? "); //user input how many grades user would like to enter
int q = in.nextInt();
double[] grades = new double[q];
double sum = 0;
for (int counter = 0; counter < q; counter++){ //user enters # of grades they requested to enter
System.out.println("Enter your grades: ");
double grade = in.nextInt();
grades[counter] = grade;
sum += grade;
}
double mean = sum / q;
System.out.println("Mean: " + mean);
for (int i = 0; i < q; i++){ //loops prints grades less than mean
if (grades[i] < mean) {
System.out.println(grades[i]);
}
}
}
Your last loop makes no sense
You should be counting through ALL the items in the array and then doing an IF to test if it's below the mean and then printing it if it is below the mean
You have made the loop iterate from 0 up to the mean.. that just makes no sense it's like saying the mean score among a group of students was 30% now print all the grades from student0 to student30 That makes no sense to do that. You should be interested in student 31 and student 32.. dont' stop at student number 30. student1 might have a grade above the mean and student 40 may have a grade below the mean. you're mixing up the student number(the index of the location in the array) with the grade.
ADDED
You are actually doing even worse than that..because grades isn't even an array it is a variable with one number in it. You have an array that increments a variable and prints the variable like printing 1,2,3,4,5
You're meant to do a loop i=1 to n, and print array[i]
You are doing a loop i=1 to n and you are printing i
You should figure out what an array is all about rather than worrying about calculating a mean. Make your own simpler exercises testing what you do/don't understand rather than something out of a book or something the teacher gave you. And use your explorations to understand this exercise your teacher/book gave you.
Your code had some issues. First off your array was being initialized with every iteration for a new grade being entered, which would result in one index since the previous inputs were overriding it. The array scores should be initialized outside the for loop.
Also, your for loop for printing out the grades wasn't correct. You needed to iterate over the scores array and print out each individual value.
The code below works and demonstrates where you went wrong:
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
double[] scores = new double[q];//initialize here
// user enters # of grades they requested to enter
for (int i = 0; i < scores.length; i++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
scores[i] = grades;//append values to each index
// adds up all elements (grades)
total += scores[i]; //sums up entered grades
}
total = total / q; //calcs mean
System.out.println("Mean: " + total);
//iterate through the scores array with filled values
for (int i = 0; i < scores.length; i++) {
System.out.println("Grade #" + i + ": " + scores[i]);
}
}
what might be the problem of that .. the total and average is wrong.
import java.io.*;
class overloading2
{
String name;
int year;
String section;
String subject[];
double grade[];
double average;
public void enrolSubjects()throws Exception
{
DataInputStream mat=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 subject:");
subject=new String[3];
for(int sub=0;sub<3;sub++)
{
subject[2]=(mat.readLine());
}
}
catch(IOException ioe)
{
}
}
public double enterGrades(double grade1,double grade2,double grade3)
{
DataInputStream math=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 grades:");
grade=new double[3];
for(int x=0; x<3; x++)
{
grade[2]=Double.parseDouble(math.readLine());
}
}
catch(IOException ioe)
{
}
return enterGrades();
}
double enterGrades()
{
double total=0.0;
for(int x=0; x<3; x++)
{
total+=grade[2];
average=total/3;
}
return average;
}
public static void main(String []args)throws Exception
{
overloading2 ostud1=new overloading2();
double a=0.0,b=0.0,c=0.0;
ostud1.enrolSubjects();
ostud1.enterGrades(a,b,c);
System.out.println("average grade is "+ostud1.enterGrades());
}
}
I have to save 10 numbers entered by a user into an array using a for loop. After that, I have to use an enhanced for loop to find the largest and smallest values in the array. I don't know how to save numbers in an array. I also have problems finding the smallest and largest values from the array and displaying them. I got an error on the for loop section where I set highestvalue and lowestvalue=inputnumber.
Here is my code:
import java.util.Scanner;
public class ArrayTester
{
public static void main(String[] args)
{
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[inputNumber] = inputNumber;
//for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
//{
//largestNumber=inputNumber;
//smallestNumber=inputNumber;
//}
}
System.out.printf("%s%8s\n", "index", "value");
System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
}
}
Replace
number[inputNumber] = inputNumber;
with
number[counter] = inputNumber;
and thats it. As for finding mix and max, use Collections.sort() on your array. First element will be min, and the last max.
Change
number[inputNumber] = inputNumber;
to
number[counter] = inputNumber;
You want to add each new number to the counter position of the array.
As for finding the minimum, maximum. The same loop that reads the inputs into the array can do that. Initialize largestNumber to Integer.MIN_VALUE and smallestNumber to Integer.MAX_VALUE. Then, each time you get a new number, compare it to both largestNumber and smallestNumber, and update them if the new number is higher/lower respectively.
assuming that you don't have to store the numbers in the same order in which they were entered by the user, you would make a sorted insert. that means, for each value entered, find the index at which this number can be inserted while maintaining a sorted array (if there exists a number at this index you have to move it move it to the right)
provided a sorted array you can find min and max in O(1):
min = number[0];
max = number[n-1];
make the following changes
//create a scanner object
Scanner input= new Scanner (System.in);
//declare largestNumber
int largestNumber;
//declare smallestNumber
int smallestNumber ;
//declare inputNumber
int inputNumber = 0;
//declare array named number and set it to 10
int[] number = new int[10];
//display message
System.out.print ("Enter an integer: ");
//column headings
for (int counter = 0; counter < number.length; counter++)
{
//set number equal to next input
inputNumber = input.nextInt();
number[counter] = inputNumber;
// for loop that will check for largest and smallest no
}
smallestNumber = number[0];
largestNumber = number[0];
for(int i=1; i< number.length; i++)
{
if(number[i] > largestNumber)
largestNumber = number[i];
else if (number[i] < smallestNumber)
smallestNumber = number[i];
}
// System.out.printf("%s%8s\n", "index", "value");
// System.out.printf("%5d%8d\n", counter, number[inputNumber]);
System.out.printf("The largest value in the array is %d\nThe smallest value in the array is %d\n", largestNumber, smallestNumber);
Also: you cannot use a for loop in this way
for (number[inputNumber]>=largestNumber && number[inputNumber]>=smallestNumber)
this is a conditional case not a loop
I would suggest you to try out this one.Let me know if it works.:-
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int num[]=new int[10];
int max=0,min=0;
for(int i=0;i<10;i++){
System.out.println("Enter number:-");
num[i]=in.nextInt();
if(num[i]>=max)
max=num[i];
if(num[i]<=min)
min=num[i];
}
min=num[0];
for(int i=0;i<10;i++){
if(num[i]<=min)
min=num[i];
}
System.out.println("The array elements are:-");
for(int i=0;i<10;i++)
System.out.print(num[i]+" ");
System.out.println();
System.out.println("Largest is:-"+max+" "+"Smallest is:"+min);
}
}
I'm trying to create a code that lets the user determine the size and elements of an array and then print it out. So far I have this.
import java.util.Scanner;
public class test3 {
public static void main (String[] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
System.out.println(values[i]);
}
}
}
I don't know if it is right because when a user inputs the size and then the elements, the code is just displaying the element as the user inputs it. For example,
input how many numbers you want to find the median for
5
please enter 5 numbers
3//user input
3//what is displayed.
I want to make it so that the user inputs all of their numbers and THEN it displays the inputed numbers as an array.
We are not allowed to use the array class by the way.
import java.util.Scanner;
public class test3 {
public static void main (String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.println("Input how many numbers you want to find the median for (numerical value) :");
int num = keyboard.nextInt();
System.out.println("Please enter " + num + " numbers.");
int[] values = new int[num];
for (int i = 0; i < num; i++) {
values[i] = keyboard.nextInt();
}
for (int i = 0; i < num; i++) {
System.out.println(values[i]);
}
}
}
Your for loop will execute for as many number as the user has entered, in your test case 5. Every iteration will take a number from the keyboard input, place it into the array and display it. Since you want to capture all the numbers first and then want to display them you should remove
System.out.println(values[i]);
from the for loop and place that into another for loop to display the numbers like so
for(int x=0 ;i < num ; i++)
{
System.out.println(values[x]);
}
This way the first loop will gather all the numbers and after the numbers are collected the second loop will display the numbers one by one iterating over the array.
Hope this helps!