Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Well, the program that follows, when run, will let me ‘roll a pair of dice’ n-times (i.e.
generate a number between 1 and 6), where n is a positive integer entered. The
program then outputs the pair of numbers (‘rolled dice’), as well as the sum of the numbers
(each pair of dice). The pairs of numbers are stored in a 2-dimensional array, and the sum
of each pair are stored in a single-dimensional array.
import java.util.Scanner;
import java.util.Random;
public class diceProblem{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of times a pair of dice will roll: ");
int times = input.nextInt();
int[][]dicePairs = rollDicePairs(times);
System.out.println("The rolled pairs of numbers are: ");
printDicePairs(dicePairs);
int[][]dicePairsSums = addDicePairs(dicePairs);
System.out.println("The sum of each pairs of numbers are: ");
printDicePairsSums(dicePairsSums);
}
public static int[][]rollDicePairs(int times){
int[][]dice = new int[times][2];
Random die = new Random();
for(int x=0;x<times;x++){
for(int y=0;y<2;y++){
dice[x][y] = 1+die.nextInt(6);
}
}
return dice;
}
public static void printDicePairs(int[][]dicePairs){
for(int[]pair: dicePairs){
for(int roll: pair){
System.out.print(roll+" ");
}
System.out.println("");
}
}
public static int[][]addDicePairs(){
int[]pairSums = new int[dicePairs];
for(int x=0;x<pairSums.length;x++){
int sum = 0;
for(int y=0;y<dicePairs[x].length;y++){
sum += dicePairs[x][y];
}
pairSums[x] = sum;
}
return pairSums;
}
public static void printDicePairsSum(int[]dicePairsSums){
for(int sum: dicePairsSums){
System.out.print(sum+" ");
}
}
}
The problem is there are too many errors with this program and it doesn't run or output the pairs of number and the sum
You code does not compile. Below is the corrected code that does compile and it also produces the correct results when you run it. Compare it to your code so as to spot the differences.
import java.util.Random;
import java.util.Scanner;
public class DiceProb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of times a pair of dice will roll: ");
int times = input.nextInt();
int[][] dicePairs = rollDicePairs(times);
System.out.println("The rolled pairs of numbers are: ");
printDicePairs(dicePairs);
int[] dicePairsSums = addDicePairs(dicePairs);
System.out.println("The sum of each pairs of numbers are: ");
printDicePairsSum(dicePairsSums);
}
public static int[][] rollDicePairs(int times) {
int[][] dice = new int[times][2];
Random die = new Random();
for (int x = 0; x < times; x++) {
for (int y = 0; y < 2; y++) {
dice[x][y] = 1 + die.nextInt(6);
}
}
return dice;
}
public static void printDicePairs(int[][] dicePairs) {
for (int[] pair : dicePairs) {
for (int roll : pair) {
System.out.print(roll + " ");
}
System.out.println("");
}
}
public static int[] addDicePairs(int[][] dicePairs) {
int[] pairSums = new int[dicePairs.length];
for (int x = 0; x < pairSums.length; x++) {
int sum = 0;
for (int y = 0; y < dicePairs[x].length; y++) {
sum += dicePairs[x][y];
}
pairSums[x] = sum;
}
return pairSums;
}
public static void printDicePairsSum(int[] dicePairsSums) {
for (int sum : dicePairsSums) {
System.out.print(sum + " ");
}
}
}
Related
I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
public static void inputThenPrintSumAndAverage (){
Scanner scanner = new Scanner(System.in);
int count =0;
int sum =0 ;
long average = 0;
boolean isAnInt = scanner.hasNextInt();
while (true) {
count++;
int number = scanner.nextInt();
if (isAnInt) {
sum+=number;
average = Math.round((sum/count));
} else {
break;
}
scanner.nextLine();
}
System.out.println("SUM = "+sum+ " AVG = "+average);
scanner.close();
}
When I am giving it a string it gives exception and doesn't even execute the "sum and avg" values. How can I change the code to make it work? If I have some wrong conceptual knowledge please help me understand the concept. Thank you.
You do not need Scanner#hasNextInt for Scanner(System.in). Also, you do not need the check, if (isAnInt). Instead, you should put a try-catch block.
You should not close Scanner(System.in); otherwise, there is no way to open it again without restarting the JVM.
Both the above thing are required when you use the Scanner for a File.
Demo:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
long average = 0;
while (true) {
try {
int number = scanner.nextInt();
sum += number;
count++;
} catch (InputMismatchException e) {
break;
}
}
average = Math.round((sum / count));
System.out.println("SUM = " + sum + " AVG = " + average);
}
}
A sample run:
2
3
5
8
abc
SUM = 18 AVG = 4
Note: you can get a better precision for average if you declare it as double and store the floating-point calculation into it without rounding e.g.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
double average = 0;
while (true) {
try {
int number = scanner.nextInt();
sum += number;
count++;
} catch (InputMismatchException e) {
break;
}
}
average = (double) sum / count;
System.out.println("SUM = " + sum + " AVG = " + average);
}
}
A sample run after this change:
2
3
5
8
abc
SUM = 18 AVG = 4.5
It will also be useful for you to understand this concept.
I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}
in my program im able to deal 5 random cards to players but i was wondering how can i incorporate a deck shuffle in my program because in my way of randomizing i tend to end up with repeated cards
import java.util.Scanner;
public class Prog2d {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int userChoice;
String[] suit = {"Clubs","Diamonds","Hearts","Spades"};
String[] faces = {"2","3","4","5","6","7","8","9","10","Jack","King","Queen","Ace"};
String[][] deck = new String[faces.length][suit.length];
System.out.println("Program 2d, Christian Villa, masc1854");
userChoice = in.nextInt();
while(userChoice > 0)
{
for(int k = 0; k < 5;k++)
{
int i = (int)(Math.random()*suit.length);
int j = (int)(Math.random()*faces.length);
System.out.println(faces[j] + " of " + suit[i]);
}
userChoice--;
System.out.println();
}
}
}
You can shuffle using the Collections.shuffle the array first and then iterate without using the Math.random method:
while(userChoice > 0)
{
Collections.shuffle(Arrays.asList(suit));
Collections.shuffle(Arrays.asList(faces));
for(int k = 0; k > 4;k++)
{
System.out.println(faces[k] + " of " + suit[k]);
}
userChoice--;
System.out.println();
}
Note: Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:
Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered. After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.
This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);
public static int[] userIntegers() // this method will build the array of integers, stopping when an out-of-range input is given
{
System.out.println("Enter the number of integers to be recorded: ");
int numInts = scan.nextInt();
int[] userArray = new int[numInts];
int i = 0;
while(i < numInts)
{
System.out.println("Enter an integer between 1-50 inclusive: ");
int userInteger = scan.nextInt();
if(isValidInteger(userInteger))
{
userArray[i] = userInteger;
i++;
}
else if(isValidInteger(userInteger) == false)
{
System.out.println("Try again.");
}
}
return userArray;
}
public static void occurrenceOutput(int[] input) // this method will print the occurrence data for a given array
{
int[] occurrenceArray = new int[51];
int j = 0;
while(j < 51) // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
{
for(int eachInteger : input)
{
occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1: occurrenceArray[j];
}
j++;
}
int k = 0;
for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
{
if(eachOccurrence > 1)
{
System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
}
k++;
}
}
public static boolean isValidInteger(int userInput) // checks if a user input is between 0-50 inclusive
{
boolean validInt = (51 >= userInput && userInput >= 0)? true: false;
return validInt;
}
public static void main(String[] args)
{
occurrenceOutput(userIntegers());
}
}
Can someone point me in a more elegant direction?
EDIT: Thanks for the help! This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
public static void main(String[] args)
{
getUserInputAndPrint();
getIntFreqAndPrint(intArray, numberOfInts);
}
private static int numberOfInts;
private static int[] intArray;
private static int[] intFreqArray = new int[51];
public static void getUserInputAndPrint()
{
// The user is prompted to choose the number of integers to enter:
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Integers: ");
numberOfInts = input.nextInt();
// The array is filled withchInteger = integer; integers ranging from 0-50:
intArray = new int[numberOfInts];
int integer = 0;
int i = 0;
while(i < intArray.length)
{
System.out.println("Enter integer value(s): ");
integer = input.nextInt();
if(integer > 50 || integer < 0)
{
System.out.println("Invalid input. Integer(s) must be between 0-50 (inclusive).");
}
else
{
intArray[i] = integer;
i++;
}
}
// Here the number of integers, as well as all the integers entered are printed:
System.out.println("Integers: " + numberOfInts);
int j = 0;
for(int eachInteger : intArray)
{
System.out.println("Index[" + j + "] : " + eachInteger);
j++;
}
}
public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
// Frequency of each integer is assigned to its corresponding index of intFreqArray:
for(int eachInt : intArray)
{
intFreqArray[eachInt]++;
}
// Average frequency is calculated:
int totalOccurrences = 0;
for(int eachFreq : intFreqArray)
{
totalOccurrences += eachFreq;
}
double averageFrequency = totalOccurrences / numberOfInts;
// Integers occurring more than once are printed:
for(int k = 0; k < intFreqArray.length; k++)
{
if(intFreqArray[k] > 1)
{
System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
}
}
// Average occurrence of integers entered is printed:
System.out.println("The average occurrence for integers entered is " + averageFrequency);
}
}
You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
To calculate occurences, you can do something like this:
for(int eachInteger : input) {
occurrenceArray[eachInteger]++;
}
This will replace your while loop.