I am a bit confused on how I would take the randomly generated number in a range from my program, store that into an array, and read and print out from the array how many times that the number was generated.
For the random import I am using java.util.concurrent.ThreadLocalRandom;
public static void main(String[] args) {
char quitOption = 'q';
char continueOption = 'c';
char input;
int[] myArray;
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
if (input == continueOption || input == 'C') {
roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} else if (input == quitOption || input == 'Q') {
System.exit(0);
}
} while (continueOption == 'c' || continueOption == 'C');
}
I would use a HashMap<Integer, Integer> lets call it rollMap.
Each time you roll you get int currentRoll = randomRoll().
If I were you, I would then say:
if(rollMap.containsKey(currentRoll)){
rollMap.put(currentRoll, rollMap.get(currentRoll) + 1);
}else{
rollMap.put(currentRoll, 1);
}
You can then get how many times each number was rolled by saying:
System.out.println(rollMap.get(<rollid>));
You must figure out how to overcome two problems:
Figure out how many rolls there will be, as Array's are fixed sized
Count how many time a number is rolled
You could use a List, and then use built in methods such as Collections.frequency, or if you are confined to an Array, check to make sure that adding another number will not be out of bounds, (And if it will be then copying it to a new Array) and then iterating over the Array and counting how many times each number occurs.
However, we know the range of numbers that will occur. So why not initialize an Array with six elements, and let 0 be 1, 1 be 2, and so on. Then every time that number is rolled, we increment the index of the respective number. So something like:
int roll = ThreadLocalRandom.current().nextInt(1, 6);
arr[roll -1]++;
So if a two is rolled, we will add one to the 1th index:
[0, 1, 0, 0, 0, 0]
And so on. Then when you need to count the index its a simple loop:
for(int i = 0; i < arr.length; i++) {
System.out.println(i + 1 + " occurs: " + arr[i] + " times");
}
Also you are over complicating your loop. It can be simplified to:
char input;
int[] myArray = new int[6];
Scanner console = new Scanner(System.in);
do {
int roll = ThreadLocalRandom.current().nextInt(1, 6);
System.out.println("Roll is " + roll);
myArray[roll -1]++;
System.out.println("Enter c to continue or enter q to quit ");
input = console.nextLine().charAt(0);
} while (input == 'c' || input == 'C');
for(int i = 0; i < myArray.length; i++ ) {
System.out.println(i + 1 + " occurs: " + myArray[i] + " times");
}
Sample run:
Roll is 4
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 3
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
c
Roll is 1
Enter c to continue or enter q to quit
q
1 occurs: 3 times
2 occurs: 0 times
3 occurs: 2 times
4 occurs: 1 times
5 occurs: 0 times
6 occurs: 0 times
Related
Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);
I'm having some trouble getting the correct output format for my homework. Here it is:
Write a program that accepts an integer n and an integer m from user and that prints a
complete line of output reporting the first m multiples of n. For example, if user input is:
m = 5, n = 3;
It should produce this output:
The first 5 multiples of 3 are 3, 6, 9, 12, and 15.
This is what I have so far:
import java.util.*;
public class Assignment2Part3 {
public static void main (String[] args) {
//declaring the two variables being entered
int n = 0;
int m = 0;
//declaring answer variable
int a = 0;
//declaring scanner input
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number you want to find multiples of");
n = input.nextInt();
while(true) {
System.out.println("Please enter the amount of multiples you want to see");
m = input.nextInt();
if (m <= 0) {
System.out.println("Please enter an integer greater than zero");
}
if (m > 0) {
break;
}
}
System.out.println("The first "+n+ " multiples of "+m+" are: ");
for (int i=1; i<=m; i++) {
a =i*n;
System.out.println(a);
}
}
}
This is what the output looks like right now:
Please enter the number you want to find multiples of
3
Please enter the amount of multiples you want to see
5
The first 3 multiples of 5 are:
3
6
9
12
15
How do I get the output to look like "The first 5 multiples of 3 are 3, 6, 9, 12, and 15." ?
NOTE: This assignment is for an introductory course and we have just covered for loops.
Printing them out on one line.
By changing System.out.println to System.out.print you can make multiple prints display on the same line.You also need to print a separator (", ") before every number (except the first), so that the numbers don't just pile up on top of each other.
Before the last number, you want to print "and".
You can do by altering the behaviour when the loop is at the final step (which is when i==m).
This gives something like this:
System.out.println("The first "+m+ " multiples of "+n+" are: ");
for (int i = 1; i <= m; ++i) {
if (i > 1) {
System.out.print(", ");
if (i==m) {
System.out.print("and ");
}
}
System.out.print(i*n);
}
System.out.println(".");
import java.util.Scanner;
import java.util.Arrays;
public class AttendanceManager {
public static void main(String args[])
{
System.out.println("Enter the number of students that are to be recorded.");
Scanner studentNum = new Scanner(System.in);
int x = studentNum.nextInt();
final int number[] = new int[x];
for(int i=0; i<x; i++)
{
System.out.println("Enter 1 if the student is present and 0 if the student is not.");
final Scanner attendance = new Scanner(System.in);
int inp = attendance.nextInt();
int y = inp;
switch (inp)
{
case 1:
number[y] = 1;
y = y++;
break;
case 0:
number[y] = 2;
y = y++;
break;
default:
System.out.println("Please enter 1 or 0.");
i--;
}
}
System.out.println("Total Students: " + number.length);
for(int k=0; k<number.length; k++)
{
if (number[k] == 1)
System.out.println("Student " + (k+1) + " is " + "present.");
else if (number[k] == 2)
System.out.println("Student " + (k+1) + " is " + "absent.");
else
System.out.println("error");
}
}
}
Output:
Enter the number of students that are to be recorded.
5
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
1
Enter 1 if the student is present and 0 if the student is not.
0
Total Students: 5
Student 1 is absent.
Student 2 is present.
error
error
error
why do the last 3 not get assigned to 1 or 0?
You're using the WRONG array index:
int inp = attendance.nextInt();
int y = inp;
switch (inp)
{
case 1:
number[y] = 1;
y = y++;
y is the value the user input, e.g. 1 or 0, which you then use as your number array index. But since the user only enters 1 or 0, you NEVER set array indexes 2, 3, 4, etc... So you're trying to output array entries that never got defined.
It should be
number[i] = 1;
^--
You are introducing another counter y which has no use, just keep the i one alone.
As the possible values of y where 0 or 1 , none of the other indexes of your array would be populated correctly.
Even worse with your current code :
Index 0 will always contain 1 if 0 was provided (0 otherwise)
Index 1 will always contain 2 if 1 was provided (0 otherwise)
Other indexes are never populated, and will always contain 0.
for(int i=0; i<x; i++)
{
System.out.println("Enter 1 if the student is present and 0 if the student is not.");
final Scanner attendance = new Scanner(System.in);
int inp = attendance.nextInt();
//int y = inp;
switch (inp)
{
case 1:
number[i] = 1;
break;
case 0:
number[i] = 2;
break;
default:
System.out.println("Please enter 1 or 0.");
i--;
}
}
Write a java programs that prompts the user to enter user's name and 4 numbers, reads them, then prints the smallest and largest of all the numbers typed in by the user. The program will continue looping if the largest number is greater or equal to 10. At the end, program will show how many times the program has looped. How can i loop and find how many times the program looped ?
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest = num[0], largest = num[0];
do{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
}
}
Output :
Enter your name : testing
testing, Please enter 4 numbers
Enter 1 : 2
Enter 2 : 6
Enter 3 : -5
Enter 4 : 16
Largest : 16
Smallest : 0
Enter your name : google
google, Please enter 4 numbers
Enter 1 : 5
Enter 2 : 8
Enter 3 : 1
Enter 4 : 6
Largest : 16
Smallest : 0
Enter your name : ....
The program become infinite loop. It should stop whenever user enter numbers that less than or equal to 10. The Largest and Smallest also does not right, when user enter <= 10 in next loop number. It will display a previous value or Largest. Also , the smallest keep display a 0 value.
First of all the assignment:
int smallest = num[0], largest = num[0];
is not dynamic in nature. Meaning the value of smallest and largest is not going to change everytime the value of num[0] changes. You need to do that manually everytime new values are entered.
Secondly you have not used any variable to actually count the number of loops.
Making these changes your code should look something like this:
package com.abhinav.testing;
import java.io.*;
import java.util.*;
class largestLoop
{
public static void main(String [] args) throws IOException
{
String name;
int[] num = new int[4]; // save 4 number in array
int smallest=0,largest=0;
int count=0;
do{
count++;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name : ");
name = stdin.readLine();
System.out.println(name + ", Please enter 4 numbers");
// Read for number using for loop
Scanner inData = new Scanner(System.in);
for(int i = 0; i < num.length; i++)
{
System.out.print("Enter " + (i+1) + " : "); // value i will + 1
num[i] = inData.nextInt();
}
smallest = num[0];
largest = num[0];
// Find larger and smallest
for (int i : num)
{
if (i < smallest)
{
smallest = i;
} // end finding smallest
else if (i > largest)
{
largest = i;
} // end finding largest number
} // end finding largest and smallest values
System.out.println("Largest = " + largest);
System.out.println("Smallest = " + smallest);
}while(largest >= 10);
System.out.println("Number of times the loop ran= "+count);
}
}
I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number cannot be larger than 1000. Both numbers must be divisible by 10. I have found a way to meet these conditions, however if they are not met my program just tells the user that their input was incorrect. Is it possible for me to code it so that after the user inputs it will check to make sure the conditions are met, and if they are not loop back and make them input again. Here is the code I have so far.
Scanner keyboard = new Scanner(System.in);
int startr;
int endr;
System.out.println("Enter the Starting Number of the Range: ");
startr=keyboard.nextInt();
if(startr%10==0&&startr>=0){
System.out.println("Enter the Ending Number of the Range: ");
endr=keyboard.nextInt();
if(endr%10==0&&endr<=1000){
}else{
System.out.println("Numbers is not divisible by 10");
}
}else{
System.out.println("Numbers is not divisible by 10");
}
Easy with do-while:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
System.out.println("Enter the Starting Number of the Range: ");
startr = keyboard.nextInt();
if(startr % 10 == 0 && startr >= 0)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
good = false;
do
{
System.out.println("Enter the Ending Number of the Range: ");
endr = keyboard.nextInt();
if(endr % 10 == 0 && endr <= 1000)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
// do stuff
You need to use a while, something like:
while conditionsMet is false
// gather input and verify
if user input valid then
conditionsMet = true;
end loop
should do it.
The all-purpose procedure is:
Read the input in an infinite loop.
Use a break; statement to exit the loop when the conditions are met.
Example:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
for (;;) {
System.out.println("Enter the starting number of the range: ");
startr = keyboard.nextInt();
if (startr >= 0 && startr % 10 == 0) break;
System.out.println("Number must be >= 0 and divisible by 10.");
}
for (;;) {
System.out.println("Enter the ending number of the range: ");
endr = keyboard.nextInt();
if (endr <= 1000 && endr % 10 == 0) break;
System.out.println("Number must be <= 1000 and divisible by 10.");
}
If after invalid input you want to display just the error message without repeating the initial prompt message, move the initial prompt message just above/outside the loop.
If you do not have need for the separate error message, you can re-arrange the code to use a do-while loop to check the conditions, which is just a little shorter:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
do {
System.out.println("Enter the starting number of the range.");
System.out.println("Number must be >= 0 and divisible by 10: ");
startr = keyboard.nextInt();
} while (!(startr >= 0 && startr % 10 == 0));
do {
System.out.println("Enter the ending number of the range.");
System.out.println("Number must be <= 1000 and divisible by 10: ");
endr = keyboard.nextInt();
} while (!(endr <= 1000 && endr % 10 == 0));