The file numbers.text consists of sequences of numbers, each sequence preceded by a header value and followed by that many integers. Read in the sequences and print their averages. When all sequences have been read in, print out the number of sequences processed.
For example, if the file numbers.text contains:
3 1 2 3
5 12 14 6 4 0
10 1 2 3 4 5 6 7 8 9 10
1 17
2 90 80
The program should produce the following output:
The average of the 3 integers 1 2 3 is 2.0
The average of the 5 integers 12 14 6 4 0 is 7.2
The average of the 3 integers 1 2 3 4 5 6 7 8 9 10 is 5.5
The average of the 1 integers 17 is 17.0
The average of the 2 integers 90 80 is 85.0
5 sets of numbers processed
My code:
Scanner sc = new Scanner(new File("numbers.text"));
int count = 0;
while (sc.hasNextLine()) {
int n = sc.nextInt();
double avg = 0;
double total = 0;
System.out.print("The average of the " + n + " integers ");
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
System.out.print(x + " ");
total += x;
}
avg = total / n;
System.out.print("is " + avg + "\n");
count++;
}
System.out.print(count + " sets of numbers processed");
}
I don't know why the last line for sets of numbers processed isn't printing and why after 85.0 is printed, a new line is missing. There's also an exception in thread "main" java.util.NoSuchElementException.
Related
Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;
Overview
I'm sure this is a simple problem for most of you on here, but I have been struggling with a small spacing problem and was hoping I can learn from someone more experienced. I need to produce a triangle similar to the one below. You can see that the numbers are aligned correctly no matter the length.
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
My Code
Here is what I have so far. It isn't the prettiest, but it seems to give me the correct values at least.
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
My Results
This is the console output when 6 rows are chosen. Everything looks good until row 5 when a 2 digit number (16) appears. What are some efficient ways to align the results properly?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
You calculate length as the number of digits in rows, but it needs to be number of digits in largest number in triangle.
E.g. for rows = 6, largest number is 32, so length should be 2.
For rows = 8, largest number is 128, so length should be 3.
Largest number is 2rows, which in Java means 1 << rows, so change length calculation to:
int length = ("" + (1 << rows)).length();
You are also adding one too many blanks on the left.
Change code to this:
a = rows - 1;
First of all i can recommend to determine the largest number in pyramid. Then count digits in this number. For 8 rows this number is 128, it has 3 digits. According this information we can decide that we need 3+1=4 (including spaces) characters to print every value in pyramid.
After it you have to complete every output number by spaces (from the left) to achive string size of 4 characters.
And the global prefix for every pyramid line will contain (rows - i) * 4 spaces.
I need to print out this shape using nested for loops for homework (full disclosure.)
I cant figure out how to center the whole thing though.
The periods represent a continuation of the pattern. So it's supposed to be the whole pyramid.
Here's what I have so now
public static void question4(){
int ix = 30;
for(int i = 1; i<=128; i=i*2){
// x is the number printed
//it gets the value from i,
for (int g = ix; g>=0; g--){
System.out.print(" ");
}
for (int x2 =1; x2<=i-1; x2=x2*2){
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x>=1; x=x/2){
System.out.print(" ");
System.out.print(x);
}
ix=ix-4;
System.out.println();
}
Thanks for the help with the decrementing spaces, now the numbers themselves push the bottom rows over however. I tried using the string.length command suggested by another user but it kept returning an error.
Try something like this:
public static void main(String[] args) {
String spacer = " ";
for (int i = 1; i <= 128; i = i * 2) {
// x is the number printed
// it gets the value from i,
System.out.print(spacer);
for (int x2 = 1; x2 <= i - 1; x2 = x2 * 2) {
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x >= 1; x = x / 2) {
System.out.print(" ");
System.out.print(x);
}
if ((i * 2) < 10)
spacer = spacer.substring(0, spacer.length() - 2);
else if ((i * 2) < 100)
spacer = spacer.substring(0, spacer.length() - 3);
else
spacer = spacer.substring(0, spacer.length() - 4);
System.out.println();
}
}
This will create space for each row decreasing the space as you go down the triangle.
Gives this for output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I know it is very easy to answer it. First check this code
int spaces = 7;
for(int i = 1; i<=128; i=i*2){
for(int k=1;k<=spaces;k++)
System.out.print(" ");
spaces--;
// x is the number printed
//it gets the value from i,
for (int x2 =1; x2<=i-1; x2=x2*2){
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x>=1; x=x/2){
System.out.print(" ");
System.out.print(x);
}
System.out.println();
}
As you can see whenever the first loop starts iterating, nested for loop for space start giving space before the another nested loop print the numbers. As the loop move further spaces will get decremented and your pyramid will grow eventually.
Although answered & accepted, here's a solution that prints a perfect pyramid with one for loop
public static void perfectPyramid() {
int upLimit = 1024;
int blankFieldWidth = String.valueOf(upLimit).length() + 1; // if upLimit is 3-digit, the blank field will be 4-blanks
String blank = new String(new char[blankFieldWidth]).replace("\0", " "); //one-liner for creating a String by repeating another String a given number of times
String numPart = "1" + new String(new char[blankFieldWidth - String.valueOf(blankFieldWidth - 1).length()]).replace("\0", " ");
String previous = "-"; // dummy initial value
for (int i = 1; i <= upLimit; i = i * 2) {
int countOfBlankFields = (int) (Math.log(upLimit / i) / Math.log(2)); // the count of blank columns per row (one side only)
String dynSpacer = new String(new char[blankFieldWidth - String.valueOf(i).length()]).replace("\0", " ");
numPart = numPart.replace(previous, previous + i + dynSpacer + previous);
String blanks = new String(new char[countOfBlankFields]).replace("\0", blank);
String row = blanks + numPart + blanks;
previous = i + dynSpacer;
System.out.println(row);
}
}
it prints a pyramid taking into account the spaces
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 512 256 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 512 1024 512 256 128 64 32 16 8 4 2 1
For what concerns the nested-loops, you can move from creating a row by replacing string into using a nested-for
How will do a program that displays a multiplication table based on the size that the user inputs? And will add each row and each column? Something like this:
Enter a number: 4
1 2 3 4 10
2 4 6 8 20
3 6 9 12 30
4 8 12 16 40
10 20 30 40
I tried this:
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = s.nextInt();
for(int i = 1; i <= x; i++)
{
for (int j = 1; j <=x; j++)
{
System.out.print((i*j) + "\t");
}
System.out.println();
}
Sample Output:
Enter a number: 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
How I will do to add each row and each column?
Since this seems like homework, I wouldn't feel comfortable writing your code for you. However, keep the following things in mind.
Your matrix will always be a square, as the user only enters a single number, of n x n numbers.
Since these numbers increment by one along the row and column, the sum of each row and column pair will be the same. In other words, the total of row[n] will equal the total of column[n].
Using that, you can create a single array of size n to store the sum of each row. For example:
Enter a number: 3
1 2 3 x
2 4 6 y
3 6 9 z
x y z
When you're looping through each row, you can store the row total in the array.
Row 0: Add 1 + 2 + 3 and store in array[0]
Row 1: Add 2 + 4 + 6 and store in array[1]
Row 2: Add 3 + 6 + 9 and store in array[2]
At the end of each row you can simply display the total in array[row]. When you finish drawing all rows, you'd simply loop through array and display each total value.
Hope this points you in the right direction!
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter size of table: ");
int x = s.nextInt();
int r = 0;
int l = 0;
int f = 0;
for(int i=1;i<=x;i++){
for (int j=1; j <=x; j++)
{
r = r + j;
System.out.print(i*j+"\t");
}
System.out.print(r);
System.out.println();
System.out.println();
l=l+i;
}
for(int k = 1; k<=x;k++)
{
f=f+l;
System.out.print(f + "\t");
}
This is the code for an upcoming university practical I have:
import java.util.Random;
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random ();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
{
count = numberGenerator.nextInt(10);
countOfArray[count]++;
arrayOfGenerator[countOfGenerator] = count + 1;
}
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
if (arrayOfGenerator[countOfOutput] == 10)
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
System.out.println("");
System.out.println("");
String occurrencesReport = "";
String graph = "";
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
occurrencesReport += "The number " + (countOfNumbers + 1) +
" occurs " + countOfArray[countOfNumbers] + " times.";
if (countOfNumbers != 9)
graph += (countOfNumbers + 1) + " ";
else
graph += (countOfNumbers + 1) + " ";
for (int a = 0; a < countOfArray[countOfNumbers]; a++)
{
graph += "*";
}
occurrencesReport += "\n";
graph += "\n";
}
System.out.println(occurrencesReport);
System.out.println(graph);
int max = 0;
int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
test = counter + 1;
}
}
System.out.println("The number that appears the most is " + test + ".");
}
}
The program creates an array that will store 100 integers (all of which are between 1 and 10), which are generated by a random number generator, and then print out ten numbers of this array per line. It then scans these integers, counts up how often each number appears and store the results in a second array.
Following this, it outputs a horizontal bar chart of asterisks showing how often each number appears before finally outputting the number that appears the most often.
I thought I had the code totally and completely done, but I've just realised that if multiple numbers occur the same amount of times, the last part of my code can't handle this, e.g. if the numbers 3 and 5 both appears 12 times, the code can only produce one of them.
Does anyone have a way around this?
Thanks,
Andrew
There are a couple of ways to address this, which range from quick to complex. The easiest way is to brute force it like such:
int max = 0;
//int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
//test = counter + 1;
}
}
System.out.print("The number that appears the most is");
boolean first = true;
for(int i = 0; i < countOfArray.length; i++)
{
if(countOfArray[i] == max)
{
if(first)
first = false;
else
System.out.print(",");
System.out.print(" " + (i+1) );
}
}
System.out.println(".");
Here's the output:
6 2 6 5 6 8 9 3 5 8
9 8 10 10 4 5 8 9 8 5
1 7 8 5 6 7 10 4 5 4
2 7 9 2 3 3 1 2 10 3
5 2 10 1 1 6 3 3 8 10
2 6 10 2 5 1 4 10 8 7
7 8 7 3 7 8 3 4 5 5
7 8 9 8 6 6 8 1 10 3
2 5 4 6 9 9 10 10 1 10
9 4 10 9 7 3 4 3 2 4
The number 1 occurs 7 times.
The number 2 occurs 9 times.
The number 3 occurs 11 times.
The number 4 occurs 9 times.
The number 5 occurs 11 times.
The number 6 occurs 9 times.
The number 7 occurs 9 times.
The number 8 occurs 13 times.
The number 9 occurs 9 times.
The number 10 occurs 13 times.
1 *******
2 *********
3 ***********
4 *********
5 ***********
6 *********
7 *********
8 *************
9 *********
10 *************
The number that appears the most is 8, 10.
There are much cleaner ways to go about it, but hopefully that gives you a decent start!
I am assuming this is not some kinda homework, so i am providing you another approach than this.
- Use Collection like ArrayList instead of Array.
- Use method like Collections.frequency(Object o) to know the number of time the value got occurred in that Collection.
Instead of just doing
System.out.println("The number that appears the most is " + test + ".");
Again loop through countOfArray, do the print for each element that has the same value as max.