Need aid with the code I wrote (need to understand) - java

The code below is what I have wrote for my assignment for class.
I have not learned from the instructor yet about the arrays, and
data. I have understood how to use the arrays, but not quite sure
about the data yet.
I have marked where I need help for the code below.
Although I have managed to write it, still not sure if it is optimal.
Could someone help me to better it perhaps?
*I asked previously about finding the mode, and people told me to do it with the
map implementation, I tried to do it, but my brain won't work for it.. any suggestions?
=================================================================================
import java.util.Scanner;
import java.util.Arrays;
public class CodeVer2 {
public static void main(String[] args)
{
Double num1, num2, num3, num4, num5, sum, avg;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first number:");
num1 = keyboard.nextDouble();
System.out.println("Enter the seond number:");
num2 = keyboard.nextDouble();
System.out.println("Enter the third number:");
num3 = keyboard.nextDouble();
System.out.println("Enter the fourth number:");
num4 = keyboard.nextDouble();
System.out.println("Enter the fifth number:");
num5 = keyboard.nextDouble();
keyboard.close();
double[] num = new double[5]; // array named num is declared with 5 variables
num[0] = num1;
num[1] = num2;
num[2] = num3;
num[3] = num4;
num[4] = num5;
Arrays.sort(num);
double[] data = {num1, num2, num3, num4, num5}; // I need help from here,
int mode = 0;
int[] index = new int[999];
int maximum = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++){
index[(int) data[i]]++;
}
for (int i = 0; i < index.length; i++){
if(maximum < index[i]){
maximum = index[i];
mode = i;
}
} // to here.
sum = num[0] + num[1] + num[2] + num[3] + num[4];
avg = sum/5;
System.out.println(" ");
System.out.println("Sum:" + sum);
System.out.println("Avg:" + avg);
System.out.println("Max:" + num[4]);
System.out.println("Min:" + num[0]);
System.out.println("Median:" + num[2]);
System.out.println("Mode:" + mode);
}
}

So all double[] does is set up an array that can contain 0 or more numbers. Think of it like a sheet of paper with a row of boxes on it. You can't add more boxes or take them away but you can write a different number in each box.
double[] data = {num1, num2, num3, num4, num5}; // I need help from here,
This creates a row of boxes, and writes the numbers in the { } into the row. It automatically creates the row to be the right size to hold the things in the brackets.
int mode = 0;
int[] index = new int[999];
int maximum = Integer.MIN_VALUE;
This creates a new list of boxes, these ones can each hold an integer and there are 999 of them.
for (int i = 0; i < data.length; i++){
index[(int) data[i]]++;
}
This loops through your data. data[i] says "use the value in the box numbered i, counting from the start of the boxes with the first box being 0".
It converts that double value to an integer and then looks up the box corresponding to that integer. It adds one to the value at that position. Note that there is a flaw in the algorithm here, if someone puts in a number over 999 then you won't have enough boxes.
for (int i = 0; i < index.length; i++){
if(maximum < index[i]){
maximum = index[i];
mode = i;
}
}
Now this loops through every box in the index array. Since earlier values are over-ridden and since you never actually calculate the maximum it actually just gives you the value in box 999 of the array and sets mode to 999. That doesn't sound very useful...

first of all I rewrote your code to make it easier to read.
What is missing is: what does this "mode" mean. I couldn't derive it from your code.
The code below is not perfect. A lot of error handling and boundary checking is missing. I leave that as an exercise for you.
So, try to understand what my code does. Think about the meaning of "mode" and how to calculate it.
import java.util.Scanner;
import java.util.Arrays;
public class CodeVer2 {
static final String CARDNAME[] = { "first", "second", "third", "fourth", "fifth" };
static final int NUM_ITEMS = 5;
public static void main(String[] args)
{
double num[], sum, avg, max, min;
double mode = 0.0; // don't know what this is
int i;
num = new double[NUM_ITEMS];
sum = 0;
max = Double.NEGATIVE_INFINITY;
min = Double.POSITIVE_INFINITY;
Scanner keyboard = new Scanner(System.in);
for (i = 0; i < NUM_ITEMS; ++i) {
System.out.println("Enter the " + CARDNAME[i] + " number:");
num[i] = keyboard.nextDouble();
sum += num[i];
if (max < num[i]) max = num[i];
if (min > num[i]) min = num[i];
}
avg = sum / NUM_ITEMS;
Arrays.sort(num);
keyboard.close();
System.out.println(" ");
System.out.println("Sum:" + sum);
System.out.println("Avg:" + avg);
System.out.println("Max:" + max);
System.out.println("Min:" + min);
System.out.println("Median:" + num[NUM_ITEMS/2]);
System.out.println("Mode:" + mode);
}
}

Related

How do I cast an int to a double?

The purpose of this program is to intake 5 values (test scores) from the user, then output the average score. I am not familiar with arrays so I really don't have the slightest clue what I'm doing wrong. All I know is the double 'sum' cannot be set equivalent to the int ' total'. Sorry for being dumb but I'M TRYING HERE :)
import java.util.Scanner;
public class Main
{
public static void main (String [] args)
{
int x = 0;
double testScore[] = new double[5];
double sum[] = new double[5];
double total;
int avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
score = testScore[i];
sum = testScore;
sum = (int)total;
avg = ((total) / 5);
System.out.print("The sum of your grades is " +avg +"\n");
}
}
}
double sum = 0;
for (double score: testScore) {
sum += score;
}
double avg = sum / testScore.length;
Here you go, I tried not to change much of your code so you can still understand what I changed!
public static void main(String[] args) {
double testScore[] = new double[5];
double sum = 0;
double avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++) {
System.out.println("Enter your grade for test number " + 1);
double score = keys.nextDouble();
sum += score;
avg = sum / 5;
System.out.print("The sum of your grades is " + avg + "\n");
}
}
Basically, all you need is the sum variable, you can get the avg from it!
first i would declare your variables like this:
int x = 0;
double[] testScore = new double[5];
double[] sum = new double[5];
double total;
int avg;
A few changes to be made:
You don't want to set score to testscore[i] because its null so flip that. If you want to cast the doubles to integers use Integer.valueOf(). You should also place them outside the for loop and calculate sum in the for loop, as shown:
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
testScore[i] = score;
sum += Integer.valueOf(score);
total += score;
}
avg = Integer.valueOf(total / testScore.length);
System.out.print("The sum of your grades is " +avg +"\n");
I haven't tested this code but i hope it helps.
In order to get the sum of all elements of an array, you will need to iterate over it:
Scanner keys = new Scanner(System.in);
double[] testScore = new double[5];
double sum = 0.0;
for (int i = 0; i < testScore.length; i++) {
// We don't need to use x, we already have i
System.out.println("Enter your grade for test number " + (i + 1));
double score = keys.nextDouble();
testScore[i] = score; // Store the grade into the element #i of the array
// We can instantly process the data we have to collect. Otherwise we must
// walk a second time over the elements
sum = sum + score; // Or the shorthand notation: sum += score
}
double avg = sum / testScore.length;
System.out.println("The average of your grades is " + avg + "\n");
I modified the following things to your code:
You are using two arrays (testScore and sum) having the same function. Both are meant to store the grades in it. I removed one of them.
I removed x, because i fulfills its function already.
I changed the type of your variable avg to a double. Feel free to change it back to an int, but then the average's decimals will be truncated (for instance, 4.6 will be 4).

How to find sum of first three digits

I'm new in Java and I try to find the sum of first three digits in int number.
I have a number 123456 I want to find the sum of first three digits 123 and then find sum of last three digits 456 and then compare it. I can't understand how to do this. I code next:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int length = (int) Math.ceil(Math.log10(number));
for (int i = 1; i <= 3; i++) {
System.out.println(i);
}
System.out.println(length);
System.out.println(number);
}
I think that I shoud to use for loop, but I'm not sure. I know how to count the length of a number. But how to how to find the sum of the first three numbers and last three?
Assuming your length is constant (6):
String first = (""+number).substring(0, 3);
String second = (""+number).substring(3, 6);
int firstSum = 0;
int secondSum = 0;
for (int x = 0; x < first.length; x++)
firstSum += Integer.parseInt(first.charAt(x)+"");
for (int x = 0; x < second.length; x++)
secondSum += Integer.parseInt(second.charAt(x)+"");
System.out.println("Sum of first 3: " + firstSum);
System.out.println("Sum of second 3: " + secondSum);
Read the String API- it has a lot of useful methods. For small programs like this, it's usually pretty easy to convert to String, use String methods, then parse back to int.
EDIT: Andy Turner and Jeremy Kato informed me about Character.getNumericValue(). Thus, the statement:
firstSum += Integer.parseInt(first.charAt(x)+"");
Could be changed to:
firstSum += Character.getNumericValue(first.charAt(x));
Likewise for secondSum.
First, probably should correct your spelling of length - though maybe not, because you don't really need that variable to do this.
What your code should do to make this easier for you is to not convert the input into an int immediately. You'll first want to split the input string into two pieces, then take the two numbers and sum them up with a loop.
Here's my idea of what I'd do:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
String input = scanner.nextLine();
String firstHalf = input.substring(0, 3); // note that depending on how
// many digits you want to change, these numbers must change as well.
String secondHalf = input.substring(3);
int sum1 = 0;
int sum2 = 0;
// don't forget: start at 0, not 1!
for(int i = 0; i<=3; i++){
sum1 += Character.getNumericValue(firstHalf.charAt(i));
sum2 += Character.getNumericValue(secondHalf.charAt(i));
// this call to the Character class converts a character to an int.
}
System.out.println(sum1);
System.out.println(sum2);
}
Just note that this code is made to work with your input being 6 characters, and it assumes they're going to be numbers. It'll crash if you enter too few characters in or if you put letters in, but you can always worry about that later.
Here's a straightforward way of doing it, making the assumption that your integer has an even number of digits...
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int[] count = new int[2];
for (int i = 0; i < s.length(); i++) {
int digit = Integer.parseInt(s.substring(i, i + 1));
int countIndex = (int)Math.floor(i * 2 / s.length());
count[countIndex] += digit;
}
int half = s.length() / 2;
System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
}
}
Alternate Method
Here's another way of doing it without using the arrays above, and actually simplified the logic by abstracting the sum to a method.
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int half = s.length() / 2;
String firstHalf = s.substring(0, half);
String secondHalf = s.substring(half);
System.out.println(firstHalf);
System.out.println(secondHalf);
int sum1 = sumString(firstHalf);
int sum2 = sumString(secondHalf);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
private static int sumString(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += Integer.parseInt(s.substring(i, i + 1));
}
return sum;
}
}
Here is an alternative solution which doesn't use Strings or arrays:
public static void main(String args[]){
int num=123456;
int second = 0;
int first = 0;
second = addLastThree(num);
num /= 1000;
first = addLastThree(num);
System.out.println("first -- > " + first);
System.out.println("second -- > " + second);
}
static int addLastThree(int num){
int sum = 0;
for (int i =0; i<3; i++){
sum += (num/Math.pow(10,i)) % 10;
}
return sum;
}
you can try this code and every line was explained in comments.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int n=number; //duplicating the value for the reference.
int l = (int) Math.log10(number) + 1; //Length of the number
int half = l/2; //to find half length of the number to sum first and last digits seperately.
int last_Sum = 0; //to store sum of last digits
int first_Sum = 0; //to store sum of first digits
for(int i=0; i<half && number>0; i++){ //to sum last digits
last_Sum = last_Sum + number%10;
number = number/10;
}for(int i=0; i<half && number>0; i++){ //to sum first digits
first_Sum = first_Sum + number%10;
number = number/10;
}
System.out.println("Length of the number "+l);
System.out.println("Number is "+n);
System.out.println("Sum of last digits "+last_Sum);
System.out.println("Sum of first digits "+first_Sum);}}

Minimum value in array java

So I need some help and maybe you guys can check my code and see why it isn't working and what I'm missing.
Here is the code:
import java.util.Scanner;
public class min;
public static void main(string[] args) {
Scanner input = new Scanner(System.in);
double[] list = new double[4];
double min = list[0];
System.out.print("Enter " + list.length + " numbers: ");
for (int i = 0; i < list.length; i++) {
list[i] = input.nextDouble();
if (list[i] < min) {
min = list[i];
}
}
System.out.println(min);
}
}
So, why does it bring back 0.0 when I have the greater than facing min?
When I flip the sign around it works and brings back the greatest number, when I put out a list of numbers it works both min and max, just not for minimum input.
You could also just initialize min as input.nextDouble after the user input, and change your for loop to start at 1

Create an array based on a range of values given by the user

What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}

Min value of array returns as 0

I'm having problems figuring out why returns for my minimum value in my array keep ending up as 0. I've checked several questions with the same problem but can't use those solutions because my array is being created in one method and my min/max values are calculated in another method.
Is there anyway I can keep my min/max value in a separate method and still get a non-zero answer for my min value? Also, there is more code in the processSalesReport method but I left it out because it was irrelevant. Thanks ahead of time!
import java.util.Arrays;
import java.util.Scanner;
public class CarSalesReport {
int sum;
int count = 0;
int[] num = new int[1500];
String ans = "";
Scanner userInput = new Scanner(System.in);
public CarSalesReport(Scanner input) {
String regex = "\\d+|done";
System.out.println("Type sales (type \"done\" when finished)");
do{
System.out.print("Sale Number " + (count + 1) + ": ");
ans = userInput.nextLine();
while(!ans.matches(regex)){
System.out.println("Please enter a positive number");
ans = userInput.nextLine();
}
if(!ans.equalsIgnoreCase("done")){
int ans1 = Integer.parseInt(ans);
num[count] = ans1;
count++;
}
}while(!ans.equalsIgnoreCase("done"));
}
public void processSalesReport(){
int max = num[0];
for(int a=0;a<num.length;a++){
if(max<num[a]){
max=num[a];
}
}
//This is where I'm having my problems.
int min = Integer.MAX_VALUE;
for(int a=1;a<num.length;a++){
if(min>num[a]){
min=num[a];
}
}
Arrays.sort(num);
System.out.println("\nMaximum sale: $" + max);
System.out.println("\nMinimum sale: $" + min);
}
}
It's because you've got 1500 entries in your array, which are all initialised to 0. You're iterating through all of them trying to find the minimum, instead of just iterating through the ones you've explicitly populated.
In the loop where you calculate the minimum, change
for (int a = 1; a < num.length; a++) {
to
for (int a = 0; a < count; a++) {
so that you only look at the entries that you've populated.

Categories