Java Assignment, lost on the math - java

I am really hoping you can help me out. I am completely lost in my assignemnt and I have been in touch with my instructor, but I still do not understand how to approach my problem. The assignment states I need:
Current Maximum of all generated random numbers so far.
(Utilize Math class to determine current Max)
Current Minimum of all generated random numbers so far.
(Utilize Math class to determine current Min)
I know I need these where I currently have Math.max & Math.min at the lower end of my code. I just am clueless on how to implement it and what the numbers represent.
import java.util.Scanner;
public class CLASS {
public static void main(String[] args) {
Scanner stdln = new Scanner(System.in);
final String HEADING_STR = "%-15s%-15s%-15s%-15s%-15s%-15s\n";
final String DATA_STR = "%-15s%-15.0f%-15s%-15s%-15s%-15s\n";
String maxRandomNumberStr; // The maximum random number to be computed (an integer to be parsed)
String amountRandomNumbersStr; // The amount of random numbers to be generated (an integer to be parsed)
int maxRandomNumber; // the integer of maxRandomNumberStr
int amountRandomNumbers; // the integer of amountRandomNumbersStr
int round = 0; // the first round
//int theMax = 0; // how to use?
//int theMin = 0; // how to use?
System.out.print("Please enter the maximum random number to be used: ");
maxRandomNumberStr = stdln.nextLine();
maxRandomNumber = Integer.parseInt(maxRandomNumberStr);
System.out.print("Please enter the number of rounds: ");
amountRandomNumbersStr = stdln.nextLine();
amountRandomNumbers = Integer.parseInt(amountRandomNumbersStr);
System.out.printf (HEADING_STR, "Round", "Round #", "Curr Max", "Curr Min", "Curr Total", "Curr Avg");
for (int i=1; i<=amountRandomNumbers; i++) {
System.out.printf(DATA_STR, round += 1, (Math.random()*(maxRandomNumber)), Math.max(?,?), Math.min(?,?), "1", "1"); // the "1"s are placeholders
}
} // end main
} // end CLASS

If I am understanding your problem correctly I think your input for Math.max() and .min() would be the newest random number being compared to the old min/max. Please see the Math class documentation here: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
I think you would need to always save any new maximum/minimum variables and compare them to the new random number each time.
int theMax = 0;
theMax = Math.max(newRandomNumber, theMax);
This will assign theMax to be the highest of the two numbers.
You can do the same for min.
Good luck.

If you're using Java 8, you ca do it easily with a Stream.
Stream.of(random1, random2, ...).max();
Stream.of(random1, random2, ...).min();
Stream.of(random1, random2, ...).avg();

Related

Cant find the percentage - JAVA

so I have this problem where finding the percentage doesn't work and I really don't know why,so my assignment is to find the number of candidates for election and the number of electors and at the end it should show the percentage of the votes example if there are 3 candidates and 6 electors and 1st candidate gets 3 votes,2nd gets 2 votes, and the 3rd gets 1 vote, it should show : 50.00%,33.33%,16.67%.
Below is my code, it gets right the number of votes but when it comes to percentage it just shows 0.0% in all cases.I hope you guys can help me out.
import java.util.Scanner;
public class ElectionPercentage {
public static void main(String[]args){
//https://acm.timus.ru/problem.aspx?space=1&num=1263
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many candidates are : ");
int candidates = sc.nextInt();
int [] allCandidates = new int[candidates];
int startingCandidate = 1;
for(int i = 0; i < candidates;i++){
allCandidates[i] = startingCandidate++; //now value of the first element will be 1 and so on.
}
//for testing System.out.println(Arrays.toString(allCandidates));
System.out.println("enter the number of electors : ");
int electors = sc.nextInt();
int [] allVotes = new int[electors];
for(int i =0;i < electors;i++){
System.out.println("for which candidate has the elector voted for :");
int vote = sc.nextInt();
allVotes[i] = vote; //storing all electors in array
}
System.out.println();
int countVotes = 0;
double percentage;
for(int i = 0;i<allCandidates.length;i++){
for(int k = 0; k < allVotes.length;k++){
if(allCandidates[i]==allVotes[k]){
countVotes++;
}
}
System.out.println("Candidate "+allCandidates[i]+" has : "+countVotes+" votes.");
percentage = ((double)(countVotes/6)*100);
System.out.println(percentage+"%");
countVotes = 0;
}
}
}
countVotes is an int 6 is also an int. Thus, (countVotes/6) which is in your code, near the end, is integer division. 11/6 in integer division is 1. 5/6 is 0. It rounds by lopping off all decimals. That's probably not what you want, especially because you try to cast it to double afterwards.
You're casting the wrong thing. But you don't even need the cast at all; if either side is double, the whole thing becomes double division. So, instead of: percentage = ((double)(countVotes/6)*100); try percentage = 100.0 * countVotes / 6.0;
Also, presumably, that 6 should really be a variable that counts total # of votes, no? i.e. electors, so: percentage = 100.0 * countVotes / electors;
The fact that we kick off the math with 100.0 means it'll be double math all the way down.
countVotes is an int. When you do (double)(countVotes/6), (countVotes/6) happens first. This evaluates to 0 since both are int. To fix this, change 6 to 6.0.
(double)(countVotes/6.0)*100
In which case, the cast to double is no longer needed.
(countVotes/6.0)*100

Sorting evens and odds between the range of two integers using while loops?

NOTE: (I do not need anyone to write the whole program for me, I only need the algorithm!)
I need to create a program that prompts the user to enter two integers. The program then needs to list all the even numbers in between the two inputed integers and output the sum. And then the same for the odd numbers. (using While loops)
I will then need to rewrite the code to use a do-while loop, and then rewrite it AGAIN using a for loop.
Here is an example of what the result should look like:
Enter an integer: 3
Enter another integer larger than the first: 10
Even Numbers: 4, 6, 8, 10
Sum of even numbers = 28
Odd Numbers: 3, 5, 7, 9
Sum of odd numbers = 24}
I tried starting off with the even numbers with something like this, but it just gets stuck at the first number, even if the first number is even.
import java.util.Scanner;
public class EvenOddSum_While {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num1 = keyboard.nextInt();
System.out.println("And another: ");
int num2 = keyboard.nextInt();
while (num1 < num2){
while (num1 %2 == 0){
System.out.print(num1 + ", ");
num1++;
}
}
}
}
The inner while has no end criteria, you need if there instead. Also, your num1++ Statement must be in the outer while loop, not the inner one.
Also, there is no real algorithm here, you're struggling with the language itself ;)
General advice: either run through your code with a step-by-step debugger, virtually every IDE has one OR place excessive log /System.out.println statements in your code to understand what it's doing
When you said 'in between' did you mean including the two integers? Because you did include them. Okay. So do this.
int x = 0;
int y = 0;
int even = 0;
int odd = 0;
int evenx = 0;
int oddx = 0;
int evena = 0;
int odda = 0;
Scanner scan = new Scanner(System.in);
//Prompts the user to input the first number
x = scan.nextInt();
//Prompts the user to input the second number
y = scan.nextInt();
for(int i = x;i<y;i++,x++;){
if(x%2 = 0){
even = even + x;
evenx++;
}
if(x%2 = 1){
odd = odd + x;
oddx++;
}
}
evena = even/evenx;
odda = odd/oddx;
//print it out. There. The algorithm.
God. Do this site have auto-format?

Taking average of user input number

This is my code
import java.util.*;
import java.io.*;
public class eCheck10A
{
public static void main(String[] args)
{
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter your integers");
out.println("Negative = sentinel");
List<Integer> aList = new ArrayList<Integer>();
for (int n1 = in.nextInt(); n1 > 0; n1 = in.nextInt())
{
if(n1 < 0)
{
break;
}
}
}
}
if i want to take all the numbers that I enter for n1, and average them out, how do i refer to all these numbers? I am going to put them in the IF statement, so if a negative number is entered, the program stops and posts their average.
This is the pseudocode you need to do this task (pseudo-code since it looks suspiciously like homework/classwork and you'll become a better developer if you nut out the implementation yourself).
Because you don't need the numbers themselves to work out the average, there's no point in storing them. The average is defined as the sum of all numbers divided by their count, so that's all you need to remember. Something like this should suffice:
total = 0
count = 0
n1 = get_next_number()
while n1 >= 0:
total = total + n1
count = count + 1
n1 = get_next_number()
if count == 0:
print "No numbers were entered.
else:
print "Average is ", (total / count)
A couple of other points I'll mention. As it stands now, your for statement will exit at the first non-positive number (<= 0), making the if superfluous.
In addition, you probably want any zeros to be included in the average: the average of {1,2,3} = 2 is not the same as the average of {1,2,3,0,0,0} = 1.
You can do this in the for statement itself with something like:
for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt())
and then you don't need the if/break bit inside the loop at all, similar to my provided pseudo-code.
An outline of what you will need to do: Create a variable sum to add up all of the values and create another variable called count that will be used to store the number of non-negative numbers in your list, aList. Then divide the sum by the count to find the average.
Another way to do running average is:
new_average = old_average + (new_number - old_average ) / count
If you ever hit max for a variable type, you would appreciate this formula.

I need to separate a integer then add the digits together in java

Good morning, I am on now to lesson 4 and am having a bit of trouble using loops. Please note that I have seen it resolved using strings but I am trying to grasp loops.
The reason for the trouble is I need to show both answers: The integer broken into individual number ex: 567 = 5 6 7
And then 567 = 18
I am able to get the integer added together but am not sure on how to separate the integer first and then add the individual numbers together. I am thinking that I need to divide down to get to 0. For instance if its a 5 digit number /10000, /1000, /100, /10, /1
But what if the user wants to do a 6 or 7 or even a 8 digit number?
Also I am assuming this would have to be first and then the addition of the individual integers would take place?
thanks for the guidance:
import java.util.Scanner;
public class spacing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
System.out.print("Enter a your number: ");
n = in.nextInt();
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Sum: " + sum);
}
}
Since this is a lesson, I won't give you the solution outright, but I will give you some hints:
You're only thinking in int. Think in String instead. :) This will also take care of the case where users provide you numbers with a large number of digits.
You will need to validate your input though; what if someone enters "12abc3"?
String.charAt(int) will be helpful.
Integer.parseInt(String) will also be helpful.
You could also look at using long instead of int; long has an upper limit of 9,223,372,036,854,775,807 though.
//I assume that the input is a string which contains only digits
public static int parseString(String input)
{
char[] charArray = input.toCharArray();
int sum = 0;
for (int index = 0; index < input.length; index++)
{
sum += Integer.parseInt(charArray[index] + "");
}
return sum;
}
Use the function above, pass your input to the function and use the output as you like.

How to find the base10 of (x:g)?

I am at the end of my homework, and a little confused on the right way to go for this algorithm. I need to find the base10 of a number:base that user gives.
Basically what my program does is take user input such as, 407:8 or 1220:5 etc.
What I am trying to output is like this.
INPUT: 407:8
OUTPUT: 407 base 8 is 263 base 10
I was thinking of this long stretched out way of doing it but I am sure there is a way easier way to go about it.
Attached is what i have so far. Thanks for looking!!
import javax.swing.JOptionPane; //gui stuff
import java.util.Scanner; // Needed for accepting input
import java.text.*; //imports methods for text handling
import java.lang.Math.*; //needed for math stuff*
public class ProjectOneAndreD //my class + program name
{
public static void main(String[] args) //my main
{
String input1; //holds user input
int val=0, rad=0, check1=0; //holds integer values user gives
and check for : handler
double answer1=0; //holds the answer!
Scanner keyboard = new Scanner(System.in);
//creates new scanner class
do //will continue to loop if no : inputted
{
System.out.println("\t****************************************************");
System.out.println("\t Loading Project 1. Enjoy! "); //title
System.out.println("\t****************************************************\n\n");
input1 = JOptionPane.showInputDialog("INPUT: ","EXAMPLE: 160:2"); //prompts user with msgbox w/ example
System.out.println("Program Running..."); //gives user a secondary notice that everything is ok..
check1=input1.indexOf(":"); //checks input1 for the :
if(check1==-1) //if no : do this stuff
{
System.out.println("I think you forgot the ':'."); //let user know they forgot
JOptionPane.showMessageDialog(null, "You forgot the ':'!!!"); //another alert to user
}
else //otherwise is they remembered :
{
String numbers [] = input1.split(":"); //splits the string at :
val = Integer.parseInt(numbers[0]); //parses [0] to int and assigns to val
rad = Integer.parseInt(numbers[1]); //parses [1] to int and assigns to rad
//answer1 = ((Math.log(val))/(Math.log(rad))); //mathematically finds first base then
//answer1 = Integer.parseInt(val, rad, 10);
JOptionPane.showMessageDialog(null, val+" base "+rad+" = BLAH base 10."); //gives user the results
System.out.println("Program Terminated..."); //alerts user of program ending
}
}while(check1==-1); //if user forgot : loop
}
}
You can use Integer.parseInt(s, radix).
answer = Integer.parseInt(numbers[0], rad);
You parse number in given radix.
It's easy, just replace your commented out logic with this:
int total = 0;
for (int i = 0; val > Math.pow(rad, i); i++) {
int digit = (val / (int) Math.pow(10, i)) % 10;
int digitValue = (int) (digit * Math.pow(rad, i));
total += digitValue;
}
and total has your answer. The logic is simple - we do some division and then modulus to pull the digit out of val, then multiply by the appropriate radix power and add to the total.
Or, if you want to make it a little more efficient and lose the exponentials:
int total = 0;
int digitalPower = 1;
int radPower = 1;
while (val > radPower) {
int digit = (val / digitalPower) % 10;
int digitValue = digit * radPower;
total += digitValue;
digitalPower *= 10;
radPower *= rad;
}
You only have implemented the user interface. Define a method taking two integers (the base and the number to convert) as argument, and returning the converted number. This is not very difficult. 407:8 means
(7 * 8^0) + (0 * 8^1) + (4 * 8^2)
You thus have to find a way to extract 7 from 407, then 0, and then 4. The modulo operator can help you here. Or you could treat 407 as a string and extract the characaters one by one and transorm each of them into an int.

Categories