How do you put a string inside a 2d Array - java

I am trying to write a polling program that takes five issues and puts the issue on the row of a 2d Array. Also how would I make the program count how many times a person rated the issue. For example if five people gave rating of five how would I write the program to count the rating and put it on the 2d Array.
These are the instructions:
Write a simple polling program that:
Allows users to rate five social-consciousness issues from 1 (least important) to 10 (most important);
Pick five causes that are important to you (e.g., political issues, global environmental issues). Use a one-
dimensional array topics (of type String) to store the five causes;
To summarize the survey responses, use a 5-row, 10-column two-dimensional array responses (of type int):
Each row corresponding to an element in the topics array.
When the program runs, it should ask the user to rate each issue. People in the range of (5, 13) have respond to the survey. Then have the program display a summary of the results, including:
a) A tabular report with the five topics down the left side and the 10 ratings across the top, listing in each column the number of ratings received for each topic.
b) To the right of each row, show the average of the ratings for that issue.
c) Which issue received the highest point total? Display both the issue and the point total. d) Which issue received the lowest point total? Display both the issue and the point total.
This is my code:
import java.util.Arrays;
import java.util.*;
public class Polling {
/**
* #param args the command line arguments
*/
public static String[] issues=new String[20];
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
issues[0]="Global Warming";
issues[1]="Earth Quakes";
issues[2]="Stopping war";
issues [3]="Equal Rights";
issues[4]="Curing Cancer";
int[][] polling =new int[5][10];
Random rand=new Random();
int random=rand.nextInt(9)+5;
int poll=0;
String polling2=Arrays.toString(polling);
for(int i=1;i<random;i++){
System.out.println("Person"+i);
System.out.println("Rate these issues from 1-10");
System.out.println(issues[0]);
int zero=console.nextInt();
System.out.println(issues[1]);
int one=console.nextInt();
System.out.println(issues[2]);
int two=console.nextInt();
System.out.println(issues[3]);
int three=console.nextInt();
System.out.println(issues[4]);
int four=console.nextInt();
}
System.out.println();

Something like this?:
public static final String[] ISSUES = {
"Global Warming",
"Earth Quakes",
"Stopping war",
"Equal Rights",
"Curing Cancer",};
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random rand = new Random();
int pollings = rand.nextInt(9) + 5;
int [][] rates= new int[pollings][ISSUES.length];
for (int i = 0; i < pollings; i++) {
System.out.println("Person" + i);
System.out.println("Rate these issues from 1-10");
for (int j = 0; j < ISSUES.length; j++) {
System.out.println(ISSUES[j]);
rates[i][j] = console.nextInt();
}
}
// ADDED
int minRating = Integer.MAX_VALUE;
int maxRating = Integer.MIN_VALUE;
int minRatingIndex = -1;
int maxRatingIndex = -1;
for (int i = 0; i < ISSUES.length; i++) {
System.out.print(ISSUES[i]+":");
int rating = 0;
for (int j = 0; j < pollings; j++) {
System.out.print("\t"+rates[j][i]);
rating += rates[j][i];
}
double average = ((double)rating)/pollings;
System.out.println("\tavr: "+average);
if (rating < minRating ){
minRating = rating;
minRatingIndex = i;
}
if (rating > maxRating ){
maxRating = rating;
maxRatingIndex = i;
}
}
System.out.println("Max points:\t"+ISSUES[maxRatingIndex]+":\t"+maxRating+" points");
System.out.println("Min points:\t"+ISSUES[minRatingIndex]+":\t"+minRating+" points");
System.out.println();
}

Related

Java lottery program, having trouble comparing outputs

I have to do an 'instant lottery' program in my first computer science class. All semester my professor has read verbatim from the book, so now I am a little lost, truthfully. I know how to do most of it, but am just having trouble figuring out array sort and how to compare user input and the random number output. My professor refuses to answer questions about take home assignments and has banned the use of anything except: arrays, loops and math.random- so no sets or anything more complex that could help. I've seen other programs that compile, but all with sets.
I have the code for user input of the lottery numbers and to generate the output of the random numbers. I can most likely also figure out how to print the payout with if/else. I just need to know how to get the program to compare the numbers an figure out if the user is a "winner" or not.
import java.util.Scanner;
public class TheLottery {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //user input of their lottery numbers
System.out.print("Enter number 1: ");
int num1 = keyboard.nextInt();
System.out.print("Enter number 2: ");
int num2 = keyboard.nextInt();
System.out.print("Enter number 3: ");
int num3 = keyboard.nextInt();
System.out.print("Enter number 4: ");
int num4 = keyboard.nextInt();
System.out.print("Enter number 5: ");
int num5 = keyboard.nextInt();
System.out.print("Enter number 6: ");
int num6 = keyboard.nextInt();
}
int[] lottery = new int[6];
int randomNum;
{
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " "); //print random numbers
}
}
the final program should have the user enter 6 numbers, the program compare the numbers for matches, figure out if the user is a 'winner', show the prize and an added thing is show how much they spent (each 'ticket' is $1) vs how much they won. So far all that outputs is the scanner and random numbers
It looks like you obtained six numbers then didn't use them. Your lottery array is automatically initialized to zero. I think you're trying to compare an array with inputs to a random array, so you need a loop to put your entered values into. After you do that, initialize your random array, then just compare the arrays.
public static void main(System[] args) {
Scanner in = new Scanner(System.in);
int[] lottery = new int[6];
System.out.println("Enter " + lottery.length + " numbers: ");
for (int i = 0; i < lottery.length; i++) {
lottery[i] = in.nextInt();
}
The specific question has to do with how to do the comparison and figuring a "winner". It isn't clear what makes the definition of "winner".
Based upon my comment, and as shown in the answer by #szoore, I would use an array to collect the input. I'd use a method to collect (since one can change to use a different method for the selections, which makes testing easier).
/**
* Obtain the specified number of entries from the user
*/
public static int[] getUserSelections(final int numSelections)
{
Scanner in = new Scanner(System.in);
// read N entries from the user
int[] nums = new int[numSelections];
// NOTE: no error processing in this loop; should be refined
// bad numbers (e.g., negative, too large), duplicate entries, etc.
// need to be removed
for (int i = 0; i < numSelections; ++i) {
System.out.print("Enter number " + (i + 1) + ": ");
nums[i] = in.nextInt();
}
return nums;
}
The OP has a basic generation for the lottery numbers, but again I'd use a method. This has a slight refinement to the duplicate check, by using a method, and also allows the same duplicate check method to be later used for checking matches:
public static int[] getLotteryNumbers(final int numSelections)
{
// the largest number to be selected; all numbers between
// 1 and maxNum (inclusive) will have equal(-ish) probability
// of being generated
final int maxNum = 50;
int[] lottery = new int[numSelections];
Random rnd = new Random();
// make N random selections, and ensure we don't have duplicates
for (int i = 0; i < numSelections; ++i) {
boolean generate = true;
while (generate) {
int sel = rnd.nextInt(maxNum) + 1;
generate = numberInArray(sel, lottery);
if (! generate) {
lottery[i] = sel;
}
}
}
return lottery;
}
/**
* Returns true if the specific queryNum is found in the pastSelections
* Could be slightly optimized by passing how many selections have
* already been made
*/
public static boolean numberInArray(int queryNum, int[] pastSelections)
{
// look at each element and see if already there; exit via return
// if so
for (int i = 0; i < pastSelections.length; ++i) {
if (pastSelections[i] == queryNum) {
return true;
}
}
return false;
}
The use of the method 'numberInArray' then allows for fairly easy check on how many numbers match:
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
Determining payouts, etc. is straight forwarding using if/else or (perhaps better) a switch based on the number of matches.
Also, the entries and lottery selections should probably be sorted. It isn't clear if the built-in sort may be used or not. Write the sort method as appropriate:
/**
* Sorts the array; implement sorting as needed
*/
public static void sort(int[] arr)
{
Arrays.sort(arr);
}
/*
* outputs the array if one cannot use Arrays.toString(arr)
*/
public static void outputArray(int[] arr)
{
for (int i = 0; i < arr.length; ++i) {
System.out.printf("%2d ", arr[i]);
}
System.out.println();
}
Sample main:
public static void main(String[] args)
{
// how many options for the lottery; here it is 6
final int numEntries = 6;
// this method obtains from user
int[] userEntries;
userEntries = getUserSelections(numEntries);
sort(userEntries);
// display User selections
outputArray(userEntries);
int[] lottery = getLotteryNumbers(numEntries);
sort(lottery);
// display lottery numbers
outputArray(lottery);
// see how many match
int matches = 0;
// see if the user entry exists in the lottery; if so, we
// have a match
for (int i = 0; i < userEntries.length; ++i) {
if (numberInArray(userEntries[i], lottery)) {
++matches;
}
}
System.out.printf("Found %2d matches%n", matches);
//
// TODO: calculate winnings based upon the number of matches
//
}

Input inside Arrays (java)?

So, I have a very messy code. The purpose of the code is to find the minimum and maximum values of a set of numbers that the user entered using arrays. The problem is I don't know how to put the Array elements (Elements) into my array (numbersArray). Here's what I have so far :
package com.company;
import java.util.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner elements = new Scanner(System.in);
System.out.println("Enter in number of numbers:");
String num = elements.nextLine();
int numArrayElements = Integer.parseInt(num);
System.out.println("Enter in numbers please: ");
Scanner console = new Scanner(System.in);
String userInput = console.nextLine();
int Elements = Integer.parseInt(userInput);
int [] numbersArray = new int[numArrayElements];
int sum = 0;
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
numbersArray[i] = temp;
sum += temp;
}
Arrays.sort(numbersArray);
System.out.println((sum - numbersArray[numbersArray.length-1])
+ " " + (sum - numbersArray[0]));
}
}
How can I make it so that I can put Elements into numbersArray?
Your major problem is the part where you try to read values entered by the user:
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
...
}
The variable numArrayElements is of type int, you can't call a method nextInt on it, it does not exist.
The method, however, exists for objects of type Scanner, like your elements variable.
After that your code probably compiles and does something useful. At least you set the array items correctly by using
numbersArray[i] = temp;
I'm not that sure about the min/max part though. I don't get why you need the sum if you sort the array. After sorting you can just take the first (min) and last element (max) given by numbersArray[0] and numbersArray[numbersArray.length - 1].
And I'm not sure why you do the parsing stuff in between, does not seem necessary. Same holds for the second scanner, not needed since you already have one.
Let me show you a cleaner approach.
Scanner scanner = new Scanner(System.in);
// Amount of values
System.out.println("Enter amount of values:");
int amount = scanner.nextInt();
// Read values
System.out.println("Enter " + amount + " values:");
int[] values = new int[amount];
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextInt();
}
// Compute max and min
...
For the last part you have several options. The most efficient would probably be to remember it already at the moment where you read the values. Your sorting approach works too, but is much more work than needed since you don't need the order of all elements, you only need the min and max element.
Let's first do a manual approach
// Compute max and min
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int value : values) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
The second approach uses a built-in method which essentially does the same. However, it is less efficient since we will first need to built a Collection on top of the array and then do two iterations instead of only one (one for max, one for min). Also, due to the conversion we need wrapper objects Integer instead of primitive values int.
// Compute max and min
Collection<Integer> valuesAsColl = Arrays.asList(values);
int max = Collections.max(valuesAsColl);
int min = Collections.min(valuesAsColl);
The third approach uses the Java Stream API (since Java 8), looks elegant and does not need to convert stuff to Integer or Collection. But the two iterations instead of one remain.
// Compute max and min
int max = Arrays.stream(values).max();
int min = Arrays.stream(values).min();
I not understand your ask .. however this code for set array size from user and numbers of array by user..
public class JavaApplication2 {
public static int[] numbers() {
Scanner element = new Scanner(System.in);
System.out.print("please insert array long : ");
int count = element.nextInt();
System.out.print("enter numers : ");
element.nextLine(); // throw away the newline.
int [] numbers = new int[count];
Scanner numScanner = new Scanner(element.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
} else {
System.out.println("You didn't provide enough numbers");
break;
}
}
return numbers;
}
public static void main(String[] args) {
int[] numbersa = numbers();
System.out.println(Arrays.toString(numbersa));
}
}

Moving Average Using User-Input Array

I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.

Java Random Utility Generating Too Many 0's And Static Numbers

The line birthdays[j] = rnd.nextInt(365); seems to generate extra 0's in the int[] birthdays array. It also seems to add an EXTRA 0 into the array and generate static values depending on how many simulations I run and how many birthdays I generate. For instance, if I do 5 simulations and enter a 3 for the number of people in each simulation's "birthday pool" I always get an array of [0, 0, 289, 362].
Any help understanding the problem would be greatly appreciated.
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn);
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// Prompt user to provide the number of simulations and number of people and return them as an array
public static int[] promptAndRead(Scanner stdIn) {
int numberOfSimulations = 0;
while(numberOfSimulations < 1 || numberOfSimulations > 50000) {
System.out.println("Please Enter the number of simulations to do. (1 - 50000) ");
numberOfSimulations = stdIn.nextInt();
}
int sizeOfGroup = 0;
while(sizeOfGroup < 2 || sizeOfGroup > 365) {
System.out.println("Please Enter the size of the group of people. (2 - 365) ");
sizeOfGroup = stdIn.nextInt();
}
int[] simulationVariables = {numberOfSimulations, sizeOfGroup};
return simulationVariables;
}
// This is the method that actually does the calculations.
public static double compute(int numOfSims, int numOfPeeps) {
double numberOfSims = 0.0;
double simsWithCollisions = 0.0;
int matchingBirthdays = 0;
int[] birthdays = new int[numOfPeeps + 1];
int randomSeed = 0;
for(int i = 0; i < numOfSims; i++)
{
randomSeed++;
Random rnd = new Random(randomSeed);
birthdays = new int[numOfPeeps + 1];
matchingBirthdays = 0;
for(int j = 0; j < numOfPeeps; j++) {
birthdays[j] = rnd.nextInt(365);
Arrays.sort(birthdays);
}
for(int k = 0; k < numOfPeeps; k++) {
if(birthdays[k] == birthdays[k+1]) {
matchingBirthdays++;
}
}
if(matchingBirthdays > 0) {
simsWithCollisions = simsWithCollisions + 1;
}
}
numberOfSims = numOfSims;
double chance = (simsWithCollisions / numberOfSims);
return chance;
}
}
The line "birthdays[j] = rnd.nextInt(365);" seems to generate extra 0's in the int[] birthdays array.
Well, it doesn't. The array elements where zero to start with.
What that statement actually does is to generate a single random number (from 0 to 364) and assign it to one element of the array; i.e. the jth element. That is not what is required for your problem.
Now, we could fix your code for you, but that defeats the purpose of your homework. Instead I will give you a HINT:
The birthdays array is supposed to contain a COUNT of the number of people with a birthday on each day of the year. You have to COUNT them. One at a time.
Think about it ...
int arrays are by default initialized to 0 unless explicitly specified. Please see this Oracle tutorial about Arrays.
I found the problem myself. The issue was that having the "Arrays.sort(birthdays);" statement inside of a loop. That generated extra 0's.

how to shift numbers in an array to be in descending order?

Im writing a program which takes in user inputted digits to store as a high score table, the user decides how many numbers on the table, and then they type the numbers they want to appear on the table, although for some reason my code for putting the numbers on the table doesnt put the numbers in descending order as id like. I think it may be a problem with the for loops in the printHighScores function although i dont see how its wrong, it should keep comparing the numbers to see if theyre all in descending order but i think i may have made a mistake int he for loop operations...
My code inputs the size of the array, then it takes the numbers in and stores them accordingly in their array position, although it doesnt do the computation to store them in descending order?
If the user types the size of the array as 3, and inputs 100, 150, 433, I want the code to sort that so that it outputs
433
150
100
instead its printing out
100
150
433
How come the for loop computation doesnt work and is there any better way to sort out the elements in the array to make them in descending order?
this is my code here, thanks for any help:
import java.util.Scanner;
/*
* Write a program to maintain a list of the high scores obtained in a game.
* The program should first ask the user how many scores they want to maintain and then repeatedly accept new scores
* from the user and should add the score to the list of high scores (in the appropriate position) if it is higher than any of the existing high scores.
* You must include the following functions:
-initialiseHighScores () which sets all high scores to zero.
-printHighScores() which prints the high scores in the format:
“The high scores are 345, 300, 234”, for all exisiting high scores in the list (remember that sometimes it won’t be full).
-higherThan() which takes the high scores and a new score and returns whether the passed score is higher than any of those in the high score list.
-insertScore() which takes the current high score list and a new score and updates it by inserting the new score at the appropriate position in the list
*/
public class HighScores {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many values would you like to set the High Score list too?:");
int userInput = input.nextInt();
int[] zeroSet = {};
int[] setScores = intialisingHighScores(userInput, zeroSet);
System.out.println("Now Enter the high scores you wish to display:");
int[] highScores = printHighScores(setScores, userInput);
System.out.println("The high scores are:");
for (int i = 0; i <= (userInput-1); i++){
System.out.println((i+1) + ". " + highScores[i]);
}
}
public static int[] intialisingHighScores(int userInput, int[] zeroSet){
zeroSet = new int [userInput];
for (int index = 0; index <= (userInput-1); index++)
{
zeroSet[index] = 0;
}
return zeroSet;
}
public static int[] printHighScores(int[] setScores, int userInput) {
Scanner inputNo = new Scanner(System.in);
int[] setScore = {};
for (int i = 0; i <= (userInput-1); i++)
{
int scores = inputNo.nextInt();
if(scores<0){
System.out.println("No player can be that bad, please enter positive high scores only");
scores = inputNo.nextInt();
setScores[i] = scores;
}
else {
setScores[i] = scores;
}
}
for (int i = 0; i >= (userInput-1); i++){
for (int n = 0; n <= (userInput-1); n++){
if (setScore[i] < setScore[n]){
int saveNo = 0;
for (int p = (userInput-1); p >= 0; p--){
setScore[i] = saveNo;
setScore[p] = setScore[p+1];
}
setScore[userInput-1] = saveNo;
}
}
}
return setScores;
}
public static int[] higherThan(int[] printHighScores, int[] setScores){
return setScores;
}
}
Solution for Integer:
Arrays.sort(array, Collections.reverseOrder());
Or you can use Arrays.sort(array); and then reverse it.
for(int i = 0; i < array.length / 2; i++){
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}

Categories

Resources