Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Check if the sum of array is less than maximum time and if yes then the generator of the random numbers will stop and the output will be like this:
No of customer = 3
max time = 4;
customer 1 = 3
customer 2 = 1
total time = 4
//so the customer 3 a
class CstplangsBadango
package cstplangsbadango;
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class CstplangsBadango {
static int customer = 0;
static int maxTime = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.print("Enter number of customer: ");
customer = sc.nextInt();
System.out.print("Enter number of Maximum time: ");
maxTime = sc.nextInt();
System.out.println(" ");
int[] cust = new int[customer];
int j = 0;
int sum = 0;
int sum1 = 0;
int chu = 0;
for (int i = 0; i < cust.length; i++) {
cust[i] = (int) randomFill();
j += 1;
sum += cust[i];
System.out.println("Customer #" + j + " = " + cust[i]);
}
System.out.println(" ");
System.out.println("Maximum time: " + sum);
}
public static double randomFill() {
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
return randomNum;
}
}
for (int i = 0; i < cust.length; i++) {
cust[i] = (int) randomFill();
}
for (int i = 0; i < cust.length; i++) {
int newSum = sum + cust[i];
if (sum < maxTime) {
sum = newSum;
} else if(sum == maxTime) {
sum = newSum;
break;
} else {
break;
}
j++;
System.out.println("Customer #" + j + " = " + cust[i]);
}
you must exclude your statement
j+=1;
sum += cust[i];
System.out.println("Customer #" + j + " = " + cust[i])
and create another loop below your created loop when you fill your array
for(int i=0;i<cust.length;++i)
{
j+=1;
sum+=cust[i];
if(sum>=MAX_TIME)
{
i=cust.length;
System.out.println("Customer #" + j + " = " + cust[i]);
}
}
if(sum>MAX_TIME)
{
int subtractor=sum-MAX_TIME;
sum-=subtractor;
}
Related
I'm trying to print the count of numbers in the array that are greater than 5.5, but I have no idea where to start. I got the following code:
package les5;
import java.util.*;
public class Les5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("How many numbers would you like to add? ");
int totalNumbers = s.nextInt();
double[] number = new double[totalNumbers];
for (int i = 1; i <= totalNumbers; i++) {
System.out.print("Number 1 " + i + ": ");
number[i - 1] = s.nextDouble();
}
int numbCount = number.length;
double avgNumber = Arrays.stream(number).sum() / number.length;
System.out.println("Numbers count: " + numbCount);
System.out.println("Average: " + avgNumber);
}
}
At the end it has to say: "Total numbers greater than 5.5: x"
Could anyone help me out?
Just iterate over the array and at each step check whether the current array element is greater than 5.5. If it is, increase a counter variable by 1.
double[] number = {10, 2, 3, 5, 6, 5.6};
int count = 0;
for (int i = 0; i < number.length; i++) {
if (number[i] > 5.5) {
count++;
}
}
System.out.println("Total numbers greater than 5.5: " + count);
public class Les5 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("How many numbers would you like to add? ");
int N = s.nextInt();
double[] number = new double[N];
//
int greaterThan5 = 0;
for (int i = 0; i <= totalNumbers; i++) {
System.out.print("Number " + i + ": ");
number[i] = s.nextDouble();
if(number[i] >5.5)
greaterThan5++;
}
int numbCount = number.length;
double avgNumber = Arrays.stream(number).sum() / number.length;
System.out.println("Numbers count: " + numbCount);
System.out.println("Average: " + avgNumber);
System.out.println("Greater than 5: " + greaterThan5);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Prompt the user to enter the size of an array and allow the user to
input integer values to your array. Check each element if it is even
or odd. If even, print solved elemets (ascending order), If odd, get
the max and min using conditional statement. Output the result.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
System.out.println("\nOdd numbers in descending order:");
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
System.out.print(s[j] + " ");
}
}
}
I don't know how to add min/max for the Odd
If I understand your question, you could try this:
int min = Integer.MAX_VALUE; // init min to the most max value
int max = 0; // store max value
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
if (min > s[j]) {
min = s[j];
}
if (max < s[j]) {
max = s[j];
}
System.out.print(s[j] + " ");
}
}
System.out.println("min = " + min);
System.out.println("max = " + max);
Full code:
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
//===========================================
System.out.println("\nOdd numbers in descending order:");
int min = Integer.MAX_VALUE; // init min to the most max value
int max = 0; // store max value
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
if (min > s[j]) {
min = s[j];
}
if (max < s[j]) {
max = s[j];
}
System.out.print(s[j] + " ");
}
}
System.out.println(); // for new line
System.out.println("min = " + min);
System.out.println("max = " + max);
}
The solution to my problem is:
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a Value: ");
int val = s.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
System.out.println("min: " + min);
System.out.println("max: " + max);
I want to take the array of random values I've generated and print the aforementioned array with parentheses outside the longest run of the same number.
For example, if the array was [0,1,1,1,2,4,7,4] I'd like to receive 0(111)2474 as an output.
This is my code thus far.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax {
runMax = counter;
runMin = i - counter + 1;
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter - 1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
}
}
try this code:
import java.util.Arrays;
import java.util.Random;
public class Snippet {
/**
* This method will generate my random numbers for my array.
*
* #param min
* minimum random value wanted
* #param max
* maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
// Part 1 - Generate a random array of length 40 with random 1-6
// inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
// Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
// Counts the longest run of the same number. A run continues only when
// consecutive numbers have the same value.
// RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 0;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax) {
runMax = counter;
startCounter = i - counter +2;
// runMin = i-counter+1;
variableNum = array1[i];
endCounter = i+1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax
+ " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter
+ " and ends at " + endCounter);
for (int i = 0; i < array1.length; i++) {
if (i==startCounter) {
System.out.print("(");
}
System.out.print(array1[i]);
if (i==endCounter) {
System.out.print(")");
}
}
System.out.println();
// Prints the array with parentheses outside the longest run, if there
// is more than one max run, use the last one.
}
}
Okay. I think I have this. The first answer was close, but if you run the program a few times, you discover issues. There is a logic error somewhere in your above code, but I have a work around. I think it is how you get the endCounter. It seems to count odd. But I got the program to work as far as I can tell. Try this out. I have run it several times and it seems consistent.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax ){
runMax = counter;
runMin = i - counter ;// was plus one I cahnged this.
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter -1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
String output = "";// added this
for(int x = 0; x < array1.length; x++)
{
if( x == startCounter)
{
output += "("+array1[x];
}
else if( x == startCounter + runMax )
{
else if( x == startCounter + runMax )
{
if(x == array1.length-1)
{
output += ")";
}
else
{
output += ")"+array1[x];
}
}
else
{
output += array1[x];
}
}
System.out.print("\n"+output);
}
}
Here's a shorter, more generic solution. This method takes any array of ints and prints parenthesis around the longest run of numbers. If there are two runs of the same lengths it prints it around the first one.
public String makeString(int[] ints) {
if (ints.length == 0) return ""; // Quit early if there's nothing to do.
// Initialize variables.
int lastNumber = ints[0];
// We keep track of the all time best run. Defaults to first int found.
int bestStart = 0;
int bestRun = 1;
// ... as well as the current run.
int currentStart = 0;
int currentRun = 1;
String s = ""+ints[0];
// Starting from the second int, we check if the current run is continuing.
for (int i = 1; i < ints.length; i++) {
int current = ints[i];
// If the current run continues, we update currentStart/currentRun, else we reset it.
if (current == lastNumber) {
currentRun++;
} else {
currentStart = i;
currentRun = 1;
}
// Now we check if the currentRun is better than the best.
// If so, we update bestStart/bestRun.
if (currentRun > bestRun) {
bestStart = currentStart;
bestRun = currentRun;
}
lastNumber = current;
s += current;
}
// Now that we've found it, we insert parenthesis aaaaaaand we're done!
return s.substring(0, bestStart)
+"("+s.substring(bestStart, bestStart+bestRun)+")"
+s.substring(bestStart+bestRun);
}
For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;
I am not sure if what I am asking is right, but originally i had this run 5 times in the main. however i felt that a do/while loop could do the same thing. But now I cannot get the array shotsMade to change from shotsMade[0] to shotsMade[1] etc, and the shotCount to store to it. It will only store the last run of the while loop. What can I change to make those 2 items increment so the methods still calculate the data correctly
import java.util.*;
public class Final {
public static void main(String[] args) {
int myGameCounter = 1;
int [] shotsMade = new int [5];
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game
do{
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
int shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
System.out.println("");
shotsMade[0]= shotCount;// I need shotsMade[0] to change each loop, shotsMade[1], shotsMade[2], shotsMade[3], shotsMade[4]
} while (myGameCounter <=5);
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game free throws made: " + max(shotsMade));
System.out.println("Worst game free throws made: " + min(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 50");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static int average (int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
int average = total*10 / nums.length;
return average;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
public static int min(int nums[]) {
int min = nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] < min)
min = nums[i];
}
return min;
}
}
Two things:
Move myGameCounter++; just below where you set shotsMade[]
Otherwise, you are increasing the game counter to 2 before the first game finished.
It should look like:
shotsMade[myGameCounter-1]= shotCount;
myGameCounter++;
} while (myGameCounter <=5);
Set shotsMade[myGameCounter-1]= shotCount; instead of shotsMade[0]= shotCount;
Otherwise, you are overwriting the value of shotsMade[0]
This way, you are re-using a counter as index for the array. Since myGameCounter will increase by one after each game (after you changed point 1) and it starts from 1, using myGameCounter - 1 will yield the correct index for your array shotsMade.