Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have written code that printed out integers from a .dat file and moved them into a regular array and printed out the average and standard deviation. Now I want to switch from a regular array to an ArrayList. I have written the code below but doesn't seem run correctly.
.dat file includes these numbers: "51 52 55 57 58 61 62 63 66 66 66 70 72 73 74 75 75 77 77 78 79 81 82 84 86 87 88 91 94 97"
Thanks for the help!
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
for (int count = 0; count < element.size(); count++)
{
while (scanner.hasNext())
{
element.add(scanner.nextInt());
number = element.get(count);
for (int item : element){
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
sum += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt((sum / (30-1)));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
}
UPDATE***
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.text.DecimalFormat;
public class gradeSorter{
public static void main(String[] args) throws IOException {
{
DecimalFormat fmt = new DecimalFormat("0.000");
Scanner scanner = new Scanner(new File("grades.dat"));
double average;
double deviation;
double sum = 0;
int number = 0;
int newnumber = 0;
ArrayList<Integer> element = new ArrayList<Integer>();
while (scanner.hasNextInt())
{
element.add(scanner.nextInt());
}
for (int item : element){
sum += item;
System.out.println(item);
}
average = sum / element.size();
for (int i = 0; i < element.size(); i++)
{
newnumber += Math.pow((element.get(i) - average),2);
}
deviation = Math.sqrt(newnumber / (element.size()));
System.out.println("The average of these grades is : " + fmt.format(average));
System.out.println("The standard deviation of these grades is: " + fmt.format(deviation));
}
}
}
----jGRASP exec: java gradeSorter
51
52
55
57
58
61
62
63
66
66
66
70
72
73
74
75
75
77
77
78
79
81
82
84
86
87
88
91
94
97
The average of these grades is : 73.233
The standard deviation of these grades is: 12.288
----jGRASP: operation complete.
First Issue:
Your for loop doesn't even run once, since element.size() is 0 initially, so the condition of loop will be false at the first iteration only:
for (int count = 0; count < element.size(); count++)
Just remove this loop. You don't need it. An ArrayList can grow dynamically. You don't need to bother about it's size.
Second Issue:
The for loop inside your while loop is doing the danger. It will accumulate the sum of all element, after adding each element. So, your sum won't be the sum of all elements of the list. It would be sum of the elements, added many times. You should move the inner for loop outside the while:
Third Issue:
You are using scanner.hasNext() and reading an int using scanner.nextInt(). You should only test for the element type, that you are reading. Use scanner.hasNextInt() to test for any available integer to read.
Well, there might be some more. But you should first solve these issues, and run the code to see what all parts did you got right.
In all, that part of your code should be modified to:
ArrayList<Integer> element = new ArrayList<Integer>();
// Remove the for loop from here
while (scanner.hasNextInt()) { // Use scanner.hasNextInt()
element.add(scanner.nextInt());
}
for (int item : element) { // Moved this for loop outside the while loop
sum += item;
}
System.out.println(sum);
Remove your for loop and things should run just fine. Just have this:
public static void main(String[] args) throws IOException {
{
....
....
while (scanner.hasNext())
{
number = scanner.nextInt();
element.add(number);
for (int item : element)
{
sum += number;
System.out.println(number);
}
}
average = sum / element.size();
....
....
....
Also details of error you got would be useful.
Related
I have this code, and it works fine, but I want to format it so that it prints 15 numbers on each line.
I have seen it done with % or for loops, but I don't know how to use them in my code. Thank you to everyone for helping! Thank you!
import java.util.*;
import java.io.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number that you want to find all the prime numbers up to it: ");
int num = sc.nextInt();
boolean[] bool = new boolean[num];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i * i); j < num; j = j + i) {
bool[j] = false;
}
}
}
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i < bool.length; i++) {
if(bool[i]==true)
{
System.out.print(i + " ");
}
}
}
}
You can make increment a count each time bool[i] is true, then move to the next line when the count is 15 and reset the count back to 0.
Here is what your print loop would now look like:
System.out.println("List of prime numbers upto given number are : ");
int count = 0;
for (int i = 2; i< bool.length; i++) {
if(bool[i])
{
if (count == 15) {
count = 0;
System.out.println();
}
System.out.print(i + " ");
count++;
}
}
Output:
Enter the number that you want to find all the prime numbers up to it: 120
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
In the context of what you're doing the best option would be something like this:
int count = 0;
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i< bool.length; i++) {
if(bool[i]==true) {
System.out.print(i + " ");
count++;
}
if(count == 15) {
System.out.println();
count = 0;
}
}
Do it as follows:
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2, j = 1; i < bool.length; i++) {
if (bool[i] == true) {
System.out.print(i + " ");
if (j % 15 == 0) {
System.out.println();
}
j++;
}
}
A sample run:
Enter the number that you want to find all the prime numbers up to it: 200
List of prime numbers upto given number are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
53 59 61 67 71 73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173 179 181 191 193 197
199
Feel free to comment in case of doubt.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
This is the code which I tried to perform Array Left shift operation which works fine for a few inputs but as i am increasing the shift amount it gives an ArrayOutOfBoundException exception.
import java.util.Scanner;
public class ArrayShift {
public static void main(String[] args) {
int x,y;
int[] n = new int[10];
int temp = 0;
Scanner sc = new Scanner(System.in);
//x is size of array
x = sc.nextInt();
// y is the amount of shift
y = sc.nextInt();
for(int i = 0;i<x;i++)
{
n[i] = sc.nextInt();
}
//Outer forloop for shift amount = y
for(int k = 0;k<y;k++)
{
temp = n[0];
//Inner forloop for shift amount = 1
for(int i=0;i<x;i++)
{
n[i] = n[i+1];
}
n[x-1]=temp;
}
for(int i=0;i<x;i++)
System.out.print(n[i]+" ");
}
}
Output
20 10
41 73 89 7 10 1 59 58 84 77 77 97 58 1 86 58 26 10 86 51
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at ArrayShift.main(ArrayShift.java:14)
You are already declaring the size of the array as 10 in this statement:int[] n = new int[10];
which means even if you enter x value as 100 the value of the array size will still be 10. hence the Array Index out of bound exception
I have to write a program that will print out all of the composite numbers that are less than 100. I have to use nested loops to complete this program. Also, the values must be displayed in a table with 10 numbers in each column.
I have been trying this program for over a week now, and I just am completely lost, could I have some help with this?
I did the composite number part, but how exactly do you put the numbers into columns with 10 numbers in each column? Here is the code:
import java.util.Scanner;
class SwitchStatements {
public static void main(String[]Args) {
for (int i = 0; i <= 100; i++) {
for (int j = 2; j <= i/2; j++) {
if (i % j == 0) {
System.out.println(i);
break;
}
}
}
}
}
Do you mean 10 numbers per row (ie 10 columns total), or 10 numbers per column?
Assuming you mean a "table" in the output as something that looks roughly like this (with 5 columns in this example):
1 2 3 4 5
11 12 13 14 15
then I think what you want to do is keep track of how many numbers you've printed on this line, and only use System.out.println when you've printed 10 numbers, and System.out.print otherwise:
int numbersPrinted = 0;
for (int i = 0; i <= 100; i++) {
for (int j = 2; j <= i/2; j++) {
if (i % j == 0) {
if (numbersPrinted < 9) {
System.out.print(i + " ");
numbersPrinted++;
} else {
System.out.println(i);
numbersPrinted = 0;
}
break;
}
}
}
If you want the numbers to line up neatly, you can add two spaces instead of one if i is less than 10 (and therefore is only one digit).
If you actually mean you want ten numbers per column like this (again, 5 in my example instead):
1 2
3 4
5 6
7 8
9 10
then you'll need to print (number of numbers / 10 numbers per column) columns per line, so you can't print them in your nested loop like in your example. Instead, you'll need to add them to an ArrayList or similar and print them in a separate loop later:
ArrayList<int> numbersToPrint = new ArrayList<int>();
...
if (i % j == 0) {
numbersToPrint.add(i);
break;
}
...
int numbersPerRow = (numbersToPrint.size()/10);
int numbersPrinted = 0;
for (int i : numbersToPrint) {
if (numbersPrinted < (numbersPerRow - 1)) {
...
and the rest of that is the same as my first example above.
If you really want 10 numbers in each column, check this code. It can be done with less amount of cycles, but it will be even harder to understand.
What we do here is collecting all composite numbers to list. Fill a 2-dimensional array from that list in a strange order (not row by row as usual, but column by column). And then print it in the 3rd cycle in the usual order.
public static void main(String[] args) {
List<Integer> compositeNumbers = new ArrayList<>();
for (int i = 0; i <= 100; i++) {
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
compositeNumbers.add(i);
break;
}
}
}
int n = compositeNumbers.size();
int numberOfRows = 10;
int maxNumberOfColumns = (n / numberOfRows) + 1;
int[][] numbers = new int[numberOfRows][maxNumberOfColumns];
for (int j = 0; j < maxNumberOfColumns; j++) {
for (int i = 0; i < numberOfRows; i++) {
int index = i + j * numberOfRows;
if (index < n) {
numbers[i][j] = compositeNumbers.get(index);
}
}
}
for (int i = 0; i < numberOfRows; i++) {
for (int j = 0; j < maxNumberOfColumns; j++) {
if (i + j * numberOfRows < n)
System.out.print(String.format("% 3d", numbers[i][j]));
}
System.out.println();
}
}
You will get the nice output:
4 20 33 46 58 72 85 96
6 21 34 48 60 74 86 98
8 22 35 49 62 75 87 99
9 24 36 50 63 76 88 100
10 25 38 51 64 77 90
12 26 39 52 65 78 91
14 27 40 54 66 80 92
15 28 42 55 68 81 93
16 30 44 56 69 82 94
18 32 45 57 70 84 95
Edited to fix composite calculation method.
Assuming you're looking for something like this:
4 20 33 46 58 72 85 96
6 21 34 48 60 74 86 98
8 22 35 49 62 75 87 99
9 24 36 50 63 76 88 100
10 25 38 51 64 77 90
12 26 39 52 65 78 91
14 27 40 54 66 80 92
15 28 42 55 68 81 93
16 30 44 56 69 82 94
18 32 45 57 70 84 95
The first step is to divide the problem into two parts.
Generate all the composite numbers from 4 to 100.
Display all the composite numbers in columns.
You mostly did the first part. You had some errors in your for loop configuration.
You can hold all of the composite numbers in a List<Integer>.
You calculate the number of columns with this line:
int columns = (compositeNumbers.size() + columnLength - 1)
/ columnLength;
Since you have to create a full line to print it, you take the composite integer at position 0, then the composite integer at position 10 (assuming 10 numbers per column). then the composite integer at position 20, and so forth, until you have created a full line.
The last few rows may not have a number in the last column. You have to take that into account when creating a display line.
Here's the code that puts all this together. The calculateCompositeNumbers method calculates the composite numbers. The displayCompositeNumbers method displays the composite numbers in columns.
See how the method names tell you what they do.
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
public class CompositeOutput {
public static void main(String[] Args) {
CompositeOutput compositeOutput = new CompositeOutput();
List<Integer> compositeNumbers = compositeOutput
.calculateCompositeNumbers();
System.out.println(compositeOutput.displayCompositeNumbers(
compositeNumbers, 10));
}
private List<Integer> calculateCompositeNumbers() {
List<Integer> compositeNumbers = new ArrayList<>();
for (int i = 4; i <= 100; i++) {
boolean found = false;
int maximum = Math.min(i / 2, 10);
for (int j = 2; j <= maximum && !found; j++) {
if (i % j == 0) {
compositeNumbers.add(Integer.valueOf(i));
found = true;
}
}
}
return compositeNumbers;
}
private String displayCompositeNumbers(List<Integer> compositeNumbers,
int columnLength) {
String lineSeparator = System.getProperty("line.separator");
StringBuilder builder = new StringBuilder();
int columns = (compositeNumbers.size() + columnLength - 1)
/ columnLength;
for (int row = 0; row < columnLength; row++) {
int tempIndex = row;
for (int column = 0; column < columns; column++) {
if (tempIndex < compositeNumbers.size()) {
int number = compositeNumbers.get(tempIndex);
builder.append(String.format("%6d", number));
}
tempIndex += columnLength;
}
builder.append(lineSeparator);
}
return builder.toString();
}
}
I've been spinning my wheels on a homework assignment for the last 3 hours and am not making very much progress. I was wondering if someone could help nudge me in the right direction.
The assignment is to read data from a file and convert it to something that is more reader friendly. The data file looks something like this:
0.30 0.30 0.40
161
3333 70 60 50
4444 50 50 50
5555 80 90 80
0
162
1212 90 85 92
6666 60 80 90
7777 90 90 90
8888 95 87 93
9999 75 77 73
0
263
2222 90 65 75
8989 60 40 60
9090 70 80 30
0
The file contains 5 different types of numbers.
1. The three digit numbers are course numbers.
2. The four digit numbers are student numbers.
The two digit numbers are scores for assignments, mid terms, and finals for each student.
The decimals across the top are used to find the weighted average for the scores.
zeros are a break between courses.
I am supposed to read all of the data in the file and then format and output it so it's easy to read:
Grade Data For Class 161
ID Programs Midterm Final Weighted Average Programs grade
-- -------- ------- ----- ---------------- --------------
3333 70 60 50 59.00 Pass
4444 50 50 50 50.00 Fail
5555 80 90 80 83.00 Pass
Class Average: 64.00
I have the scanner setup and am able to parse out the numbers from the text, my problem is that they are all saved as Strings so I can't do any mathematical checks on them. I'm starting to wonder if this is even the best way to go about this.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class classAverage
{
public static void main(String[] args) throws IOException
{
//in variable equals entire file
Scanner in = new Scanner(new File("courseData.txt"));
int classID;
System.out.println("ID Programs Midterm Final Weighted Average Programs Grade");
System.out.println("-- -------- ------- ----- ---------------- --------------");
while(in.hasNextLine()) //While file has new lines
{
//line equals each line of text
String line = in.nextLine();
Scanner lineParser = new Scanner(line);
System.out.println(line);
for(; lineParser.hasNext();)
{
//number = each number
String number = lineParser.next();
System.out.println(number);
if(number < 1 && number > 0)
{
double programsAverage = number.nextDouble();
double midtermAverage = number.nextDouble();
double finalAverage = number.nextDouble();
System.out.println(programsAverage);
System.out.println(midtermAverage);
System.out.println(finalAverage);
}
}
}
}
}
Update I've included my updated code. My problem now is my conditions in my for statements. These should be checking the values of the incoming Scanner data to see if the data is:
a weight calculator(0,1)
a score(1,100),
a classNumber (100,400),
a studentNumber(1000,9999),
a class separator (0).
I am thinking something like:
for(in.next(); in < 100 && in > 1; next());
This isn't quite doing it though.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
/**
* Write a description of class classAverage here.
*
* #author
* #version
*/
public class classAverage
{
public static void main(String[] args) throws IOException
{
//in variable equals entire file
Scanner in = new Scanner(new File("courseData.txt"));
int classNumber;
int studentNumber;
int programs;
int midterm;
int finals;
double programWeight = in.nextDouble();
double midtermWeight = in.nextDouble();
double finalWeight = in.nextDouble();
//System.out.println(programWeight + " " + midtermWeight + " " + finalWeight);
for(int k = 0; k < 3; k++)
{
for(int i = 0; i <= 0; i++)
{
classNumber = in.nextInt();
System.out.println("Grades for class: " + classNumber);
System.out.println(" ID Programs Midterm Final Weighted Average Programs Grade");
System.out.println(" -- -------- ------- ----- ---------------- --------------");
}
int studentCount = 0;
double sumAverage = 0.0;
for(int j = 0; j <= 2; j++)
{
studentNumber = in.nextInt();
programs = in.nextInt();
midterm = in.nextInt();
finals = in.nextInt();
studentCount++;
double weightedAverage = (programWeight * programs) + (midtermWeight * midterm) + (finalWeight * finals);
sumAverage += weightedAverage;
System.out.printf("%d %d %d %d %.2f ", studentNumber,programs,midterm,finals,weightedAverage);
if(programs >= 70)
{
System.out.print("PASS");
} else {
System.out.print("FAIL");
}
System.out.println();
}
double classAverage = sumAverage / studentCount;
System.out.printf("Class average is: %.2f", classAverage);
System.out.println("\n\n");
}
}
}
You have 2 options here :
Use Scanner#hasNextInt() and nextInt() instead of nextLine() to read Integers directly instead of numbers in String format.
Keep your reading / scanning code intact. Use Integer.parseInt() to convert String to Integers. --> Preferred solution. As it is more efficient.
I'm not sure why this won't print out anything
for (int number : humidity)
{
if (sum < 12)
{
System.out.printf("%6d",humidity[sum]);
sum++;
}
}
Humidity is taken in from a file
Scanner inFileHumid = new Scanner(fileNameHumid);
int [] humidity = new int[length];
Then is set to the array
while (inFileHumid.hasNextInt())
{
humidity[n] = inFileHumid.nextInt( );
n++;
}
and the numbers from the file are 69 67 66 64 66 69 67 67 70 69 69 70 which are the ones I'm trying to get to be printed in my for each loop
You are iterating each number in humidity, but then you ignore those values and test some unrelated sum. I think you want
for (int number : humidity)
{
System.out.printf("%6d", number);
}
Or equivalently,
for (int sum = 0; sum < humidity.length; sum++)
{
System.out.printf("%6d", humidity[sum]);
}
I think you just have a problem indexing into humidity. So this should work.
for (int number : humidity){
if (number < 12) // Look at the value
{
System.out.printf("%6d", number); // Print what is in the array
}
}
Assuming sum is zero before the loop is entered, that code works.
int[] humidity = {1,2,3,4,5,6,7,8,9,0,1,2};
int sum= 0;
for (int number : humidity) {
if (sum < 12) {
System.out.printf("%6d", humidity[sum]);
sum++;
}
}
producing:
1 2 3 4 5 6 7 8 9 0 1 2
So for the code to fail sum must be greater or equal to 12 before the loop is entered.