I need the first method for generating a random number should receive the beginning and ending value of the range within its parameter list. It should send back the random number through the method name. And the second method to display the array which I have but apparently the code is not broken down into two methods and I don't understand how to accomplish this. I am lost after working on this for so long.
Here is my UPDATED code but still receiving 4 errors:
import java.util.Scanner;
import java.util.Random;
public final class {
public static Random generator = new Random();
public int createNum(int[] randomNumbers, int SIZE, int n, int i) {
int x;
SIZE = 20;
randomNumbers = new int[SIZE];
Random generator = new Random();
for (i = 0; i < SIZE; i++) {
n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
return n;
}
public void print(int i, int randomNumbers, int SIZE){
SIZE = 20;
randomNumbers = new int[SIZE];
for (i = 0; i < SIZE; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public static void main(String[] args){
do{
Scanner inputReader = new Scanner(System.in);
System.out.print("Do you wish to restart the program, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
}
First thing's first, don't put everything in main if the task is to decompose your solution. What you need is a class that exercises the logic of your requirements or at least two additional methods that perform the work independently.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
represents two distinct tasks. You can tell because they are not dependent on each other.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
int n = generator.nextInt(10) + 1;
randomNumbers[i] = n;
}
generates and places the numbers.
This code:
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
prints them.
Since it seems beneficial for you to figure this out on your own; what's needed now? hint: read the first part again
Related
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Random;
public class labb8 {
public static void main(String[] args) {
Random rnd = new Random();
int[][] sales = new int[5][7];
int[] total = new int[sales.length];
ArrayList<String> unpopularSoftware = new ArrayList<String>();
String[] locations = {"Houston", "Dallas", "Hunts", "San Ant", "Austin"};
System.out.println("Location\t| Software Sales\t\t| Total Sales");
System.out.println("--------------------------------------------------");
for (int i = 0; i < sales.length; i++) {
for (int j = 0; j < sales[i].length; j++) {
sales[i][j] = rnd.nextInt(25);
total[i] += sales[i][j];
}
System.out.print(locations[i] + "\t\t|");
System.out.print(" " + Arrays.toString(sales[i]));
System.out.println("\t| " + total[i]);
}
int unpopularModelCounter;
for (int j = 0; j < sales[0].length; j++) {
unpopularModelCounter = 0;
for (int i = 0; i < sales.length; i++) {
if (sales[i][j] != 0) {
unpopularModelCounter++;
}
}
if (unpopularModelCounter <= 3) {
unpopularSoftware.add("Software " + (j + 1));
}
}
System.out.println("Unpopular Software: " + unpopularSoftware);
System.out.println("Location with most sold licenses: ");
}
}
Above is the code and it gives me the results I'm looking for; however, I'd like to know some methods on how can I print out the name of the location that has the most sold software? What I've tried is putting System.out.println(total[i]); under System.out.println("\t| " + total[i]); but that just displayed all the totals, which is what I figured would happen. I've also tried putting System.out.println(total[i]); where the other output lines are at the bottom(which is where I want it), but the code can't find [i], which made me believe that I might have to create some methods; so, again, I'm asking for some course of advice on how to print out the name of the city with the largest amount sold in terms of my code.
If you want the name of the city the the highest total, you need to look through the total array for the largest total and, while doing that, keep track of both the largest total you've seen so far and the index at which you saw that largest total.
Something like this should do the job nicely:
// Our initial guess is that `total[0]` is the maximum sales total.
int maxSales = total[0];
int maxI = 0;
for (int i = 1; i < total.length; ++i) {
if (totals[i] > maxSales) {
maxSales = total[i];
maxI = i;
}
}
System.out.println(locations[maxI] + " has the most sales: " + maxSales);
Maybe try adding this to the end of the code.
int max = 0; // stores the maximum value
for (int i = 0; i < total.length; i++) {
max = Math.max(max, total[i]);
}
System.out.println(max);
This should print the greatest value of the total array. I like your code!
import java.util.Scanner;
public class TriangleDriver {
public static void main(String[] args) {
System.out.println("Please enter value of N: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
for (int i = 1; i <= num; i++) {
System.out.printf("%d\t", i);
}
System.out.println("");
System.out.println("---- ----");
for (int i = 0; i < num; i++) {
System.out.print((i + 1) + " ");
for (int j = 1; j <= num; j++) {
System.out.printf("%7.2f", Math.sqrt(i * i + j * j));
}
System.out.println();
}
}
}
This could be useful to others that are new to coding. I do need help on it though. When you input a number, say 8,
-it is not spaced properly
-The first actual row of data should not include 1.00, 2.00, 3.00
-Personal Preference: I would like to include ---- on the top after the i numbers and | on the side for the J numbers
What do you guys think?
This is close to how your code should look
public class TriangleDriver {
private static final String REQUEST = "Please enter value of N: ";
private static final String SPACER3 = " ";
private static final String SPACER4 = " ";
private static final String DIVIDER = "----";
private static final String FORMAT_ONE = " %d ";
private static final String FORMAT_FIRST_ROW = "%7.0f";
private static final String FORMAT_ADDITIONAL_ROWS = "%7.2f";
private static final int HEADER_LINES = 2;
public static void main(String[] args) {
int num = getIntInput(REQUEST);
StringBuilder[] result = solution(num);
printSBArray(result);
}
static private int getIntInput(String request){
System.out.print(request);
return new Scanner(System.in).nextInt();
}
static private void printSBArray(StringBuilder[] sbArray){
for (StringBuilder sb : sbArray)
System.out.println(sb.toString());
}
static private StringBuilder[] solution(int num){
StringBuilder output[] = new StringBuilder[num + HEADER_LINES];
for(int i = 0; i < output.length; i++)
output[i] = new StringBuilder("");
// build line 0
output[0].append(SPACER4 + SPACER4);
for (int i = 1; i <= num; i++) {
output[0].append(String.format(FORMAT_ONE, i));
}
// build line 1
output[1].append(DIVIDER + SPACER4);
for (int i = 0; i < num; i++)
output[1].append(String.format(DIVIDER + SPACER3));
// build line 2
int i = 0;
output[2].append((i + 1) + SPACER4);
for (int j = 1; j <= num; j++) {
output[2].append(String.format(FORMAT_FIRST_ROW, Math.sqrt(i * i + j * j)));
}
// build line 3+
for (i = 1; i < num; i++) {
output[i + 2].append((i + 1) + SPACER4);
for (int j = 1; j <= num; j++) {
output[i + 2].append(String.format(FORMAT_ADDITIONAL_ROWS, Math.sqrt(i * i + j * j)));
}
}
return output;
}
}
This gives good separation of functionality, keeps strings out of logic code, and minimizes main to only essential calls. Also uses StringBuilder to build the result. This allows you to maintain separation of functionality. Code should do one thing, ie calculate results but not print them. Technically, this should have been separated into it's own class.
On a side note, I would not turn this in as your homework your teacher might just get a bit suspicious.
Final Result:
import java.util.Scanner;
public class TriangleDriver {
public static void main(String[] args) {
System.out.println("Please enter value of N: ");
Scanner scan = new Scanner(System. in );
int num = scan.nextInt();
System.out.print("\t");
for (int i = 1; i <= num; i++) {
System.out.printf("%d\t", i);
}
System.out.println();
String barrier = "\t";
for (int i = 0; i < num; i++)
barrier += "----\t";
System.out.println(barrier);
for (int i = 0; i < num; i++) {
System.out.print((i + 1) + "");
for (int j = 1; j <= num; j++) {
System.out.printf("\t%.2f", Math.sqrt(i * i + j * j));
}
System.out.println();
}
}
}
Explanation:
First of all, you used 7.2f in your printf(), which was a pain to troubleshoot. The 7 in 7.2f states that you want the output to always be 7 spaces long, regardless of number length. This is not equal to the amount added by \t, so the columns don't line up. To create the ---- barriers under each line, I used a for loop to add N sections. It should be easy to add the |s.
In regards to
The first actual row of data should not include 1.00, 2.00, 3.00
I don't know what you really want. I'm not sure what you want the first value to be - it seems to follow the Math.sqrt(i * i + j * j) calculation that you are using to generate the data for the other rows.
I am doing a project in which the user enters a number, x ,it will then generate x amount of random numbers and add them to an arraylist. In one text field, it will display however many random integers are in the array, I then have to make it so in another textfield, it sorts those numbers through a selection sorting. I'm pretty sure I have the code for it right, I'm just not sure how to get the sorted numbers to display on the text field #2. Heres what I have:
ArrayList <Integer> Numbers = new ArrayList <Integer>();
....
String input;
int int1,int2 = 0, min = -1000, max = 1000,j, maximum;
input = Input.getText();
int1 = Integer.parseInt(input);
Random number = new Random();
while(int2 < int1){
for (int i = 0; i < int1; i++){
int randomInt = number.nextInt(max - min + 1) + min;
Numbers.add(randomInt);
int1--;
}
}
if(Selection.isSelected() && Ascending.isSelected()){
for (int i = 0; i<Numbers.size()-1; i++){
maximum = i;
for(j = i+1; j<=Numbers.size()-1;j++){
if(j < i){
int temp = i;
i = j;
j = temp;
}
}
}
}
Output1.setText("Unsorted Numbers " + Numbers);
Output2.setText("Sorted Numbers " + //what here? );
Numbers.clear();
Thanks for any help you might be able to offer.
what about this ?
public static void main(String[] args) {
//min and max value
int min = -1000;
int max = 1000;
//collection to store numbers
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random random = new Random();
//receive input
Scanner myScanner = new Scanner(System.in);
int numberFromUser = Integer.parseInt(myScanner.nextLine());
for (int i = 0; i < numberFromUser; i++) {
numbers.add(random.nextInt(max - min + 1) + min);
}
System.out.println("Unsorted :" + numbers);
// sort the numbers
Collections.sort(numbers);
System.out.println("Sorted :" + numbers);
numbers.clear();
}
You should prepare a string:
String sortedNumbersOutput = "";
for (int i = 0; i < sortedNumbers.size(); i++) {
sortedNumbersOutput += sortedNumbers.get(i) + (i != sortedNumbers.size() - 1 ? "," : "");
}
Output2.setText("Sorted Numbers " + sortedNumbersOutput );
On a separate note, I don't believe you are sorting your list...
You are comparing on the indices and not the values at those indices.
Maybe you want to try:
boolean changes = true;
int temp;
while (changes) {
changes = false;
for (int i = 0; i < Numbers.size()-1; i++){
if (Numbers.get(i) > Numbers.get(i+1)) {
temp = Numbers.get(i);
Numbers.set(i, Numbers.get(i+1));
Numbers.set(i+1, temp);
changes = true;
}
}
}
which is called a bubble sort
Ok so this is my code. I'm supposed to gather 10 numbers of input and then sort them in descending order by the number of which they appear.
Ex. {0,0,1,2,2,2]
My output would be "Mode=2 and then have 2 appears 3 times, 0 appears two times, 1 appears once."
My code can gather the 10 integers and find the mode but I'm having issues trying to sort the numbers in that way. This is what I have so far and I'm stuck.
import java.util.*;
class question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arrTwo = new int[10];
int x=0;
for (int i = 0; i < 10; i++)
{
System.out.println("Enter number: " + (i + 1));
arrTwo[i] = scan.nextInt();
}
mode(arrTwo);
int temp;
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x )
{
if (bs[x]>bs[x+1])
{
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
for(int i = 0; i <= bs.length-1; i++)
{
for(int index=0; index <= 99 ; index++)
{
if (i == i)
{
bs[i] +=1;
}
}
System.out.println("The number " + i + " is generated " +arrTwo[i] + " times");
}
}
public static void mode(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println("The mode is: "+maxIndex);
}
My output isn't listing my numbers, just 0-9 and the generated times is just going from 1-9 with no basis or order.
this code:
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x ){
if (bs[x]>bs[x+1]) {
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
does nothing. On initialization bs is filled with zeroes bs[x-1] is never greater than bs[x] because all values are the same.
also
if (i == i){
is always true
I am writing a beginner program using arrays, math.random and and random generator to calculate the sum of 2 die rolling a certain amount of times.
I am trying to calculate the percentage of times a sum shows up and need 2 decimal places. Is there a way to cast(?) and array so that it appears with 2 decimal places?
Also, when I print on screen the program it shows 120 times each sum. I dont understand why
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
public class Die {
public static void main(String[] args){
int faces;
int face1;
int face2;
int face3;
int face4;
int times;
int index;
int sum;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("%-0-1-2-3-4-5-6-7-8-9-0-1-2-3-4-5-6-7-8-9-0-%");
System.out.println("%\t\t\t\t\t %");
System.out.println("% How good is the Random Number Generator %");
System.out.println("%\t\t\t\t\t %");
System.out.println("%-0-1-2-3-4-5-6-7-8-9-0-1-2-3-4-5-6-7-8-9-0-%");
System.out.println();
System.out.print("What is the number of sides of each die? ");
faces = scan.nextInt();
System.out.print("How many times do you want to roll the dice ?");
times = scan.nextInt();
int[]rollCount = new int[(faces*2) + 1];
for (int i = 0; i<rollCount.length; i++)
rollCount[i] = 0;
int dice1=faces;
for (int k=1; k<=dice1; k++){
int dice2=faces;
for (int r=1; r<=dice2; r++){
rollCount[k+r]++;
for (int roll = 0; roll <times; roll++){
}
}
}
int[]rollCountRand = new int[(faces*2) + 1];
for (index = 0; index <rollCountRand.length; index++)
rollCountRand[index] = 0;
for (int roll = 0; roll<=times; roll++){
face1 = 1 + rand.nextInt(faces);
face2 = 1 + rand.nextInt(faces);
rollCountRand[face1 + face2]++;
}
int[]rollCountMath = new int [(faces*2)+1];
for (int i=0; i<rollCountMath.length; i++)
rollCountMath[i] = 0;
for (int j=0; j<=times; j++){
face3 = (int)(faces* Math.random() + 1);
face4 = (int)(faces* Math.random() + 1);
sum = face3 + face4;
rollCountMath[sum]++;
}
for (int r = 2; r <rollCount.length; r++){
int percent = (rollCount[r] / ((faces*faces)*100));
for (int k = 2; k <rollCountRand.length; k++){
int percentOne = rollCountRand[k] / (times/100);
for (int q = 2; q <rollCountMath.length; q++){
int percentTwo =rollCountMath[q] / (times/100);
System.out.print(r + "\t( " + rollCount[r] + ")" + "\t" + "%" + percent + "\t" + k + "\t( " + rollCountRand[k]+")" + "\t"+"%"+percentOne + "\t" + q + "\t( " + rollCountMath[q]+")" + "\t" + "%"+percentTwo);
System.out.println();
Thank You!
You can't directly cast int[] to double[], but you can cast each element as you process it, for example where you calculate the percentage, you could write int percentTwo = (int)Math.round((double)rollCountMath[q] / (times/100.0));.
As for loop counts, it looks like your code posted here is lacking some closing braces (maybe it's just a formatting error when you pasted the code), so it's hard to say how it would behave if the braces were in place.