I was wondering if it's possible to use a loop to fill and array without prompting the user for input?
I have to design a program to fill an array of size 6 with multiples of 7. The specification doesn't say anything about prompting the user, and it says 'Use a loop to fill the array' so I can't hard code the numbers in.
Of the multiples of 7 , I need to print out which ones can be divided by 3 exactly.
Is it possible to fill the array without an input from the user?
My code is below...
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 26/02/2015
* Time: 15:25
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class Array7Mult
{
public static void main(String[] args)
{
int multipleSeven [] = new int[6];
final int HOWMANY=6,DIVIDE=3;
Scanner keyboard = new Scanner(System.in);
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Please enter a multiple of 7 below..");
multipleSeven[count]=keyboard.nextInt();
}//for
System.out.println("The multiples of seven that can be divided by 3 are..");
for(int count=0;count<HOWMANY;count++)
{
if (multipleSeven[count] % DIVIDE == 0)
{
System.out.println(multipleSeven[count]);
}//if
}//for
}//main
}//class
Yes ofcourse. Say you want to populate an array by a variable which is incremented by one per index. Say variable i (so we use the same variable that's instantiated in the loop).
for(int i = 0; i < arr.length; i++)
arr[i] = i;
Simple as that. You may ofcourse create a global variable and add it into the array within the boundaries of the loop and manipulate its value within the loop too.
int a = 0;
for(int i = 0; i < arr.length; i++) {
arr[i] = a;
a += 10;
}
If you want to increment the value as a multiple of seven, you can simple use the first example and instead of doing arr[i] = i do arr[i] = i*7
Use
for(int count=0;count<HOWMANY;count++)
multipleSeven[i]=(i+1)*7;
Instead of
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Please enter a multiple of 7 below..");
multipleSeven[count]=keyboard.nextInt();
}
To fill the array multipleSeven with values 7,14,21,28,35,42.
Related
I am trying to get the number of pattern to printout from the array but under my number of pattern no pairs were printed out this is an example of what i am trying to get
(Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3)
but I do not know what to write from beyond number of patterns
The code:
public class FindIt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int Sum = 0;
int[] InsertNumbers = new int[10];
System.out.println("Sample output #1:");
System.out.print("Array: ");
for(int i = 0; i < 10; i++)
{
InsertNumbers[i]=(int)(Math.random()*10)+1;
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Array: ");
for(int i = 0; i < 5; i++)
{
ComputePattern(InsertNumbers, Sum);
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Number of patterns: ");
}
public static void ComputePattern(int[] InsertNumbers, int Sum)
{
for(int i = 0; i < 2; i++)
{
InsertNumbers[i] = Sum;
Sum = Sum + Sum;
}
}
}
It is quite hard to understand your code but here is what I can tell you.
You have managed to get to ask the user input but I feel that the following would be better.
Instead, try having two arrays, one which the user can input 10 integers, and the other array with the sum of the pairs, hence an array containing 5 integers.
With the help of a For Loop and a formula, you can use it to get the 2 consecutive values. The first formula being x*2, the second being (x*2)+1.
With x being 0 in the for loop, and loop it for 5 times.
Afterwards, you get the values of the x*2 and the (x*2)+1 in the array, and sum them together.
Then with the sum, you can then use it to calculate the count of patterns.
Suggestion : Try to be consistent with your println and print. It is quite confusing and I am not quite sure as to why you have set println for certain text and print for the rest.
No patterns were printed because you have no print statements after you print Number of patterns.
I have a task about incremental values in a loop based on user input.
The task is that the following lines are generated in the console
*
**
***
****
*****
And the amount of lines are decided by user input. I.e. if the user types in 2 it gives the following output:
*
**
My current code is:
import static javax.swing.JOptionPane.*;
public class loop1 {
public static void main(String[] args){
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
while (current_line != target_line){
String sign = "*";
System.out.println(sign);
current_line ++;
}
}
}
But I can't seem to get the number of asterisks (*) to increase for every time it runs. How can I accomplish this?
You need a nested loop. Each iteration of the outer loop (which is the loop you already have) would print a single row, and each iteration of the inner loop would print a single asterisk for the current row.
You actually need two loops here, but you only have one. You have a while loop to print out the asterisks, but you also need a loop to increment the number of asterisks printed out each time.
Some pseudocode might look like:
For (int i = 1 to whatever value the user entered):
For (int j = 1 to i):
Print an asterisk
Actual code would look like:
int numLines = Integer.parseInt(showInputDialog("type here "));
for(int numAsterisks = 0; numAsterisks < numLines; numAsterisks++) {
for(int i = 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println(); // Start a new line
}
You can make it simpler by using nested for loops. Modify your loop to:
for (int i=0;i<target_line;i++) {
for (int j=0;j<=i;j++) {
System.out.print("*");
}
System.out.println();
}
You print everytime one '*'-sign.
You don't necessarily need two loops. You can place the sign outside of the loop and you can add an asterisk every iteration with string.concat("*"). Concatenating actually means combining two strings into one, so you actually combine the sign from the previous iteration with a new sign.
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
String sign = "*";
while (current_line != target_line){
sign.concat("*");
System.out.println(sign);
current_line ++;
}
I am attempting to create a small java program where the user will enter a string of numbers such as 2 4 6 7 8 9 0 3 4 5. These numbers will be saved to an array of int[] type. I then need the program to calculate how many of each number has been entered and output 2 columns, one containing the number entered and the other containing the amount of times the individual number was entered. Using the above numbers, I need the output to be as below:
Number Times Entered
2 1
4 2
6 1
7 1
8 1
9 1
0 1
3 1
5 1
So far I am using 3 classes. An application class that contains the main method, a driver class and the class containing the logic and objects. At this stage I have only started work on the class containing the logic. The code I have so far is below:
package arrayentry;
import java.util.Scanner;
public class Entry {
private Scanner scn = new Scanner(System.in);
private int[] count = new int[51];
public void countNumberEntry(int[] countArray){
int input = scn.nextInt();
for (int i=0; i<10; i++)
if (input == i)
count[i]++;
}
public void dataEntry(){
System.out.println("Please enter numbers between 1 and 50");
count = scn.nextInt[]();
}
}
Any ideas as to how I can get this to work would be greatly appreciated, this is driving me up the wall.
Thanks.
EDIT: To elaborate, I am have issues with everything. I for some reason can't get my head around it. I have read books etc but I can't get it. I need to store the entered numbers into an array of 50, then calculate the amount of times each number is entered and output as above.
To be honest I am just trying to get a grip / start on this.
You can create another array that will store number of occurences for you
public int [] countOccurences(int originalArray[]){
int countedOccurencesArray[]= new int [51];
for(int i=0;i<originalArray.length){
contedOccurencesArray[originalArray[i]]++;
}
return countedOccurences;}
This would actually be easier with a HashMap. Every time you read a number, check to see if it's in the map. If it is, increment the count, otherwise, insert it with a count of 1.
Since this assignment requires arrays, you'll want to create 2 50-cell arrays. In 1, store the value of the number read, in the second, store the count. Put both values in the cell that corresponds with the number read. Then just print off the values you need.
package arrayentry;
import java.util.Scanner;
public class Entry {
private Scanner scn = new Scanner(System.in);
private int[] numbers = new int[51];
private int[] count = new int[51];
public Entry() {
// All counts start at 0, all numbers start at -1 (invalid, so we know it's not from user input)
for (int cell = 0; cell < count.length; cell++) {
count[cell] = 0;
values[cell] = -1;
}
}
public void dataEntry(){
System.out.println("Please enter numbers between 1 and 50");
int[] input = scn.nextInt[]();
for (int value : input) {
numbers[value] = value;
counts[value] += 1;
}
}
public void printCounts() {
System.out.println("Number\tTimes Encountered.");
for (int cell = 0; cell < numbers.length; cell++) {
// Don't print counts of any number we didn't see in the input.
if (numbers[cell] > 0) {
System.out.println(numbers[cell] + "\t" + counts[cell]);
}
}
}
}
I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.
I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.