Trouble printing out pattern in array - java

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.

Related

Creating a User-Input Asterisk Triangle using Java

I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}
Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH
Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().
In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.

Printing an array on a certain line

I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers. Also who do i Enter numbers into an array without defining how many numbers will be entered?
import java.util.Scanner;
public class NumberArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many grades do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " grades now.");
for (int grades = 0 ; grades < array.length; grades++ )
{
array[grades] = input.nextInt();
}
System.out.println("These are the grades you have entered.");
printArray(array);
}
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " \t");
}
}
}
I need help printing the array, I need to print 6 items per line and switch to a next line for the seventh and following numbers.
From this question, it seems to indicate that you want the output to look like this:
1 2 3 4 5 6
7 8 9 ... n
This can be achieved quite simply.
Option 1 - The classic If statement
for(int x = 0; x < array.length; x++) {
System.out.print(array[x]);
if(x == 5) {
// 5 because we're counting from 0!
System.out.println();
}
}
Option 2 - Using the Ternary operator to keep it on one line
NOTE: This is more or less the same. It's just nice to be complete in these sorts of answers.
for(int x = 0; x < array.length; x++) {
System.out.print(array[x] + x == 5? "\n":"");
}
Edit
If you meant that you want 6 items on each line, like so:
1 2 3 4 5 6
7 8 9 10 11 12
...
Then you can use the % (The modulus operator) to print out a new line on every output. This is actually quite easy to change, but you'll need to make sure that you're checking the value before you're outputting the content. This can be shown in this IDEOne.
Use modulus operator (%) to break to a new line line:
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++) {
if(i % 6 == 0) // if you don't want the initial newline, check for i > 0
System.out.println()
System.out.print(arr[i] + " \t");
}
}
you can also use printf() method to format the line; which is probably better:
System.out.printf("%5d", arr[i]);
The reason why this is better, is because you can easily format the output to a specific justification, column width, etc., which will make your output look better.

Java program using arrays created by data entry

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]);
}
}
}
}

Taking the average of an Array

I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)

double precision numbers into an array, then sort and display number from lowest to highest

In line 24, I am getting an error which is commented out. What is causing this and how to I get it fixed?
Any help is much appreciated. Thanks ahead of time. :)
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//initialize array
double[] numbers = new double [10];
//Create Scanner object
System.out.print("Enter " + numbers.length + " values: ");
//initialize array
for ( int i = 0; i < numbers.length; i++){
numbers[i] = input.nextDouble() ;
java.util.Arrays.sort(numbers[i]); //getting an error here, thay says [The method sort(int[]) in the type Arrays is not applicable for the arguments (double)]
//Display array numbers
System.out.print(" " + numbers);
}
//Close input
input.close();
}
}
You need to sort the complete array rather than a single element:
Arrays.sort(numbers);
Better to move it outside of the for-loop. You could use Arrays.toString to display the contents of the array itself:
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextDouble();
}
Arrays.sort(numbers);
System.out.print(Arrays.toString(numbers));
Note: Class names start with an uppercase letter, e.g. MyMain.
Put this after the for loop:
java.util.Arrays.sort(numbers);
notice numbers not numbers[i] and the print needs to come out of that loop too.
The mistake you're making is that you are trying to sort a single number. The error message points out that the sort method expects an array.
Your algorithm should first read in all the numbers, before sorting. So change your code to something like this:
...
// first read in numbers
for ( int i = 0; i < numbers.length; i++){
numbers[i] = input.nextDouble() ;
}
// then apply sort
java.util.Arrays.sort(numbers); // numbers is an array, so it's a valid argument.
// finally, after sorting you may now output the sorted array
for(int number : numbers){
System.out.println(number);
}
...

Categories