The program is supposed to return
The test scores in descending order are: (Scores) The average is
(average)
The result that I am receiving is
The average is (average) The test scores in descending order are:
(Scores)
How can I fix it to receive the proper return
import java.util.Scanner;
public class Average
{
private int[] data;
private double mean;
public Average()
{
data = new int[5];
int number = 0;
int Temp = 0;
String[] Scores = new String[5];
Scanner keyboard = new Scanner(System.in);
for(int index = 0; index < data.length; index++)
{
number++;
System.out.print("Enter test score #" + number + ":");
Temp = keyboard.nextInt();
data[index] = Temp;
}
selectionSort();
calculateMean();
}
public void selectionSort()
{
int n = data.length;
for(int index = 0; index < n-1; index++)
{
int min_idx = index;
for(int j = index+1; j < n; j++)
if(data[j] >= data[min_idx])
min_idx = j;
int temp = data[min_idx];
data[min_idx] = data[index];
data[index] = temp;
}
}
public String toString()
{
String MyScore = "Your test scores in descending order are: " + "\n";
for(int index = 0; index < data.length; index++)
{
MyScore += data[index] + " ";
}
return MyScore;
}
public void calculateMean()
{
int Sum = 0;
int Mean = 0;
for(int index = 0; index < data.length; index++)
{
Sum += data[index];
}
Mean = Sum/data.length;
System.out.println("The average is " + mean);
}
}
What would I have to swap around in order to make this work?
Edit: The Average class is used in this file
public class AverageDriver
{
public static void main(String[] args)
{
Average MyScores = new Average();
System.out.print(MyScores);
}
}
You should call calculateMean() only after calling toString().
So you can either modify the constructor
selectionSort();
System.out.println(toString());
calculateMean();
or calling only selectionSort(); in the constructor, then in your main
public class AverageDriver
{
public static void main(String[] args)
{
Average myScores = new Average();
System.out.print(myScores);
myScores.calculateMean();
}
}
By the way, you should use lowercase name for variables, this will fix the error in calculateMean(): you are calling System.out.println("The average is " + mean); but the variable is Mean.
The error why it's not printing the correct average lies in this method:
public void calculateMean() {
int Sum = 0;
int Mean = 0;
for (int index = 0; index < data.length; index++) {
Sum += data[index];
}
Mean = Sum / data.length;
System.out.println("The average is " + mean);
}
You're printing out mean which is defined globally, but never initialized so it defaults to 0. In this method you have the variable Mean (capitalized) which is the variable the actual value is stored in, that's the variable you want to print.
public static void main(String[] args)
{
Average MyScores = new Average();
System.out.print(MyScores);
}
When you create the Average instance the constructor is called. In the constructor there is a call to calculateMean(), which prints
The average is (average)
When you print MyScores the override toString() is being called, which prints The test scores in descending order are: (Scores).
Take out the methods calls out of the constructor (they shouldn't be there in the first place) and call them from main
public static void main(String[] args)
{
Average myScores = new Average();
System.out.print(myScores);
myScores.selectionSort();
myScores.calculateMean();
}
I am new to Java, and in creating a program to print 6 random numbers for a lottery ticket, i am receiving an ArrayIndexOutOfBounds error that i cannot figure out how to fix. Here is what I have.
import java.util.Random;
public class DebugMeOne {
static int[] lottoNumbers = new int[6];
public static void main(String[] args)
{
generateNumbers();
printNumbers();
}
private static void generateNumbers()
{
int ticketNumber;
Random generateRandomNumber = new Random();
for (int count = 0; count < lottoNumbers.length + 1; count++)
{
ticketNumber = 1 + generateRandomNumber.nextInt(59);
lottoNumbers[count] = ticketNumber;
}
}
private static void printNumbers()
{
for (int count = 0; count < lottoNumbers.length + 1; count++)
{
if (count < 5)
if (count == 4)
System.out.print(lottoNumbers[count]);
else
System.out.print(lottoNumbers[count] + ", ");
else
System.out.println("\nPower Ball: "
+ lottoNumbers[count]);
}
}
}
I also have another program i had to create for the same thing, just a little bit different code. I am getting an error in that as well:
public class Lottery {
static ArrayList<Integer> lottoNumbers = new ArrayList<Integer>();
static int MAX_NUMBERS = 6;
public static void main(String[] args)
{
generateNumbers();
printNumbers();
}
private static void generateNumbers()
{
int ticketNumber;
Random generateRandomNumber = new Random();
for (int count = 0; count < MAX_NUMBERS; count++)
{
ticketNumber = 1 + generateRandomNumber.nextInt(59);
lottoNumbers.add(new Integer(ticketNumber));
}
}
private static void printNumbers()
{
int count = 0;
for( Integer number : numbers ) // enhanced for loop
{
if (count < 5)
if (count == 4)
System.out.print(number);
else
System.out.print(number + ", ");
else
{
System.out.println("\nPower Ball: " + number);
count++;
}
}
}
}
In this i am getting this error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code
cannot find symbol
symbol: variable numbers
location: class debugmetwo.DebugMeTwo
at debugmetwo.DebugMeTwo.printNumbers(DebugMeTwo.java:52)
at debugmetwo.DebugMeTwo.main(DebugMeTwo.java:34)
Java Result: 1
Your for loop count is exceeding over the array's length. Both the for loops should be run like
for (int count = 0; count < lottoNumbers.length; count++)
Also, you shouldn't hardcode your length values (5, 4) used in your count comparisons for printing commas. Use the length property as
for (int count = 0; count < lottoNumbers.length; count++)
{
if (count < lottoNumbers.length - 1) {
System.out.print(lottoNumbers[count]);
System.out.print(count == lottoNumbers.length - 2 ? "" : ", ");
} else {
System.out.println("\nPower Ball: "
+ lottoNumbers[count]);
}
}
Your loop's condition should be :
for (int count = 0; count < lottoNumbers.length; count++)
The valid indices of lottoNumbers are from 0 to lottoNumbers.length - 1.
I'm trying to figure out how to go about using these methods to complete this assignment but I'm still relatively new with Java and don't know where to go with it. The array file we have is: 2D Array
Here is the assignment: Assignment
I am just looking for some insight on the math and what to use to get started with these methods. I'm not asking for anyone to do my homework! Thanks for any help in advance!
Here is what I have so far:
public static void main(String[] args) throws FileNotFoundException {
File skyimage = new File("skyimage.txt");
Scanner scan = new Scanner(skyimage);
int r, c;
r = scan.nextInt();
c = scan.nextInt();
int sky[][] = new int[r][c];
for(r = 0; r < sky.length; r++){
for(c = 0; c < sky[r].length; c++)
sky[r][c] = scan.nextInt();
}
printArray(sky);
lightSource(sky, c);
}//end main
private static void printArray(int[][] sky) {
for(int r = 0; r < sky.length; r++){
for(int c = 0; c < sky[r].length; c++){
System.out.printf("%5d", sky[r][c]);
}
System.out.println();
}
}
public static void lightSource(int sky[][], int n){
Point[] lightPoint = new Point[n];
for(int r = 0; r < sky.length; r++){
for(int c = 0; c < sky[r].length; c++){
new Point(r, c);
}
}
System.out.println("The brightest interior point is located at: " + lightPoint);
}//end method
public static void darkSource(){
}//end method
public static void filterImage(){
}//end method
public static void negativeImage(){
}//end method
Once you have read the input, all you need is just a few utility methods
(like sum, getNeighbours and isValidPoint) and a few loops.
Here is a sketch (not a full-blown solution).
In it I have hard-coded the sample sky input.
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
public class Test045 {
private static int[][] sky = {
{10,2,2},
{10,5,1},
{1,2,2}
};
public static void main(String[] args) {
Point min = null;
Point max = null;
Integer sumMin = null;
Integer sumMax = null;
Integer s = null;
for (int i=0; i<sky.length; i++){
for (int j=0; j<sky[0].length; j++){
s=sum(getNeighbours(i, j));
if (sumMin==null || sumMin > s){
min = new Point(i,j);
sumMin = s;
}
if (sumMax==null || sumMax < s){
max = new Point(i,j);
sumMax = s;
}
}
}
System.out.println("Max Light at: " + max.x + ", " + max.y +
" ; MAX Light = " + sumMax);
System.out.println("Min Light at: " + min.x + ", " + min.y +
" ; MIN Light = " + sumMin);
}
private static int sum(List<Point> lst){
int sum = 0;
for (Point p : lst){
sum += sky[p.x][p.y];
}
return sum;
}
private static List<Point> getNeighbours(int ip, int jp){
List<Point> lst = new ArrayList<Point>();
for (int i=-1; i<=1; i++){
for (int j=-1; j<=1; j++){
if (isValidPoint(ip+i, jp+j)){
lst.add(new Point(ip+i, jp+j));
}
}
}
return lst;
}
private static boolean isValidPoint(int i, int j){
return
i >= 0 && i < sky.length &&
j >= 0 && j < sky[0].length;
}
}
I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}
I am trying to solve a problem by fetching the maximum number from each row in a triangle. So far am able to generate a triangle but how do I fetch the max number from each row?
Here is my code
private static Integer solve(Triangle triangle)
{
//triangle is extending an ArrayList
System.out.println(triangle);
return 0;
}
This is what am producing so far:
6
3 5
9 7 1
4 6 8 4
but now I want to get the result which says:
"In this triangle the maximum total is: 6 + 5 + 9 + 8 = 26"
Here is the complete code:
public class HellTriangle {
private static final int TRIANGLE_HEIGHT = 10;
public static void start() {
Triangle triangle = generateTriangle();
//System.out.println(triangle);
long start = System.currentTimeMillis();
Integer result = solve(triangle);
long end = System.currentTimeMillis();
System.out.println("Result:" + result);
System.out.println("Resolution time: " + (end - start) + "ms");
}
private static Triangle generateTriangle() {
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
for (int j = 0; j <= i; j++) {
row.add(random.nextInt(100));
}
triangle.add(row);
}
return triangle;
}
private static class Row extends ArrayList<Integer> {
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
sb.append(String.format("%02d", get(i)));
//rows.add(get(i));
if (i < (size() - 1)) {
sb.append(" ");
}
}
return sb.toString();
}
}
private static class Triangle extends ArrayList<Row> {
public String toString() {
// sb is used to make modification to the String
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size(); i++) {
for (int j = 0; j < (TRIANGLE_HEIGHT - 1 - i); j++) {
sb.append(" ");
}
sb.append(get(i));
if (i < (size() - 1)) {
sb.append("\n");
}
}
return sb.toString();
}
}
private static Integer solve(Triangle triangle) {
System.out.println(triangle);
return 0;
}
public static void main(String[] args) {
start();
}
}
Any help would be appreciated!
Here, just change with your solve()
private static void solve(Triangle triangle) {
System.out.println(triangle);
ArrayList<Integer> result = new ArrayList<Integer>();
int total = 0;
for(Row row : triangle){
Collections.sort(row);
total += row.get(row.size()-1);
result.add(row.get(row.size()-1));
}
for(Integer intr : result)
System.out.println("Largest elements of the rows: " + intr);
System.out.println("Total: " + total);
}
As there is no ordering in your rows and this would lead to O(n) to get the maximum value per row i would look up the maximum value during insertion. Something like that (not tested and you probably have to override the other add methods also, depending on your use case):
public class Row extends ArrayList<Integer> {
public String toString() {
...
}
private Integer max = null;
#Override
public boolean add(Integer elem) {
if (elem != null && (max == null || max < elem)) {
max = elem;
}
return super.add(elem);
}
public Integer getMax() {
return max;
}
}
Try
private static int getTriangleMax(final Triangle rows)
{
int max = 0;
for (final Row row : rows)
{
final int rowMax = getRowMax(row);
max += rowMax;
}
return max;
}
private static int getRowMax(final Row row)
{
int rowMax = Integer.MIN_VALUE;
for (final Integer integer : row)
{
if (rowMax < integer)
{
rowMax = integer;
}
}
return rowMax;
}
Simple-Solution:
1.Add the static list as here:
private static List maxRowVal=new ArrayList();
2.Replace your generateTriangle() function with this:
private static Triangle generateTriangle()
{
Triangle triangle = new Triangle();
Random random = new Random();
for (int i = 0; i < TRIANGLE_HEIGHT; i++) {
Row row = new Row();
int maxTemp=0;
for (int j = 0; j <= i; j++) {
int rand=random.nextInt(100);
row.add(rand);
if(rand>maxTemp)
maxTemp=rand; //will get max value for the row
}
maxRowVal.add(maxTemp);
triangle.add(row);
}
return triangle;
}
Simple indeed!!
This is not exactly what you asked for, but I would like to show you a different way to go about this problem. People have done this for me before, and I really appreciated seeing different ways to solve a problems. Good luck with your coding!
Below is the code in its entirety, so you can just copy, paste and run it.
public class SSCCE {
public static void main(String[] args) {
// Here you specify the size of your triangle. Change the number dim to
// whatever you want. The triangle will be represented by a 2d-array.
final int dim = 5;
int[][] triangle = new int[dim][dim];
// Walks through the triangle and fills it with random numbers from 1-9.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
triangle[r][c] = (int) (9 * Math.random()) + 1;
}
}
// This piece just prints the triangle so you can see what's in it.
for (int r = 0; r < dim; r++) {
for (int c = 0; c < r + 1; c++) {
System.out.print(triangle[r][c] + " ");
}
System.out.println();
}
// This part finds the maximum of each row. It prints each rows maximum
// as well as the sum of all the maximums at the end.
int sum = 0;
System.out.print("\nIn this triangle the maximum total is: ");
for (int r = 0; r < dim; r++) {
int currentMax = 0;
for (int c = 0; c < r + 1; c++) {
if (triangle[r][c] > currentMax) {
currentMax = triangle[r][c];
}
}
sum += currentMax;
if (r != 0) {
System.out.print(" + ");
}
System.out.print(currentMax);
}
System.out.println(" = " + sum + ".");
}
}
Output:
9
9 2
1 7 3
1 7 3 3
5 7 5 1 9
In this triangle the maximum total is: 9 + 9 + 7 + 7 + 9 = 41.