My team is making a project that displays big digits in hash codes.
We imported a local library: ScoreboardNumbers
Example, if the user enters 4, the output is:
#
# #
# #
# #
# # # # #
#
#
So the program is here below and we can't seem to find out what the problem is with one of the lines. I posted the whole code just in case we messed up somewhere else.
Thanks for helping guys!
//Main class
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
System.out.print("Digit: ");
int dig = scanIn.nextInt();
Score digit = new Score(dig);
digit.getScoreArray();
String strDigit = ScoreboardNumbers.get(Digit.getScoreArray()); //Red squiggly under the '.getScoreArray()'
Scanner scanStr = new Scanner(strDigit);
int col = 0;
while (scanStr.hasNextInt()) {
System.out.print(scanStr.nextInt() == 1 ? " #" : " ");
col++;
if (col % 5 == 0) {
System.out.println();
}
}
}
//Instantiable class Digit
public class Digit {
private int digit;
private final int ROWS = 7;
private final int COLS = 5;
public Digit(int digit) {
this.digit = digit;
}
public boolean[][] getDigitArray() {
boolean[][] arr = new boolean[ROWS][COLS];
String strDigit = ScoreboardNumbers.get(digit);
Scanner scanStr = new Scanner(strDigit);
int col = 0;
int row = 0;
while (scanStr.hasNextInt()) {
arr[ROWS][COLS] = (scanStr.nextInt() == 1);
col++;
if (col % 5 == 0) {
col = 0;
row++;
}
}
return arr;
}
}
//Class: Score
public class Score {
private int score;
public Score(int score) {
this.score = score;
}
public boolean[][][] getScoreArray() {
int digit1 = score / 10;
int digit2 = score % 10;
Digit d1 = new Digit(digit1);
Digit d2 = new Digit(digit2);
boolean[][][] scoreArray = {
d1.getDigitArray(),
d2.getDigitArray()
};
return scoreArray;
}
}
First you have to know the difference between instance method and static method.
A. Static Method
Static method are those which are declared with the static keyword.
Static method can be called by using the instance, instance variable or the class name.
Example :
public class MyCalculator{
public static int powerOf(int number, int power){
.... some code here...
}
public static void main(String[] args){
MyCalculator x = new MyCalculator();
int answer1, answer2, answer3;
answer1 = x.powerOf(3, 6); //Correct
answer2 = MyCalculator.powerOf(4, 2); //Correct
answer3 = new MyCalculator().powerOf(4, 2); //Correct
}
}
B. Instance Method
Instance method is declared without the static keyword.
Can be called by an instance or instance variable.
Example :
public class MyCalculator{
public int powerOf(int number, int power){
.... some code here...
}
public static void main(String[] args){
MyCalculator x = new MyCalculator();
int answer1, answer2, answer3;
answer1 = x.powerOf(3, 6); //Correct
answer2 = MyCalculator.powerOf(4, 2); //FALSE
answer3 = new MyCalculator().powerOf(4, 2); //Correct
}
}
The line String strDigit = ScoreboardNumbers.get(Digit.getScoreArray()); on your code calls the static method getScoreArray() from the class Digit which does not exist, thus, generates an error.
It looks like you might be trying to access a method that's not static as if it were a static method. You need to call the getScoreArray() function on an actual Score instance, not on the class itself. Perhaps you want the 'digit' object? In which case it would be digit.getScoreArray(), rather than Score.getScoreArray().
1 getScoreArray() belongs to Score class not digit class
2 getScoreArray() is not static method.
Related
I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}
The numThrows Variable is inciting an error of variable not found when used in the main method. even though i declare it in one of the methods.
I use the declare the variable in the void prompt method. This program is designed to calculate Pi using random coordinates then uses a formula to estimate pie over a user given amount of tries.
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts
public static void prompt()
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
}
public static double[] randomX( int numThrows)
{
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts <= numThrows)
{
cordX[i] = Math.random();
i++;
}
return cordX;
}
public static double[]randomY(int numThrows)
{
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts <= numThrows)
{
cordY[i] = Math.random();
i++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY)
{
int ii = 0;
int i = 0;
double hits = 0;
double misses = 0;
for(i = 0; i <= numThrows; i++)
{
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1)
{
hits++;
ii++;
}
else{
misses++;
}
}
}
public static double calcPi(int misses, int hits)
{
int total = hits + misses;
double pi = 4 * (hits / total);
}
// public static void print(double pi, int numThrows)
// {
// System.out.printf(" %-7s %3.1f %7s\n", "Trial[//numtrial]: pi = "
// }
public static void main(String[] args)throws IOException
{
prompt();
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
gethits();
double pi = calcPi(misses, hits);
}
}
If numThrows is declared within another function, then its scope does not extend to the main method.
Instead, if you want to use it in both the main method and the other one, make it a class instance.
For example:
class SomeClass {
public static int numThrows = 2;
public static void test() {
numThrows = 4; // it works!
}
public static void main(String[] args) {
System.out.println(numThrows); // it works!
}
}
Therefore, its scope will be extended to all the members of the class, not just the method.
numThrows is an instance variable to your prompt method. If you want to do what I think you want to do, make numThrows a static variable outside any methods.
It will look like this:
public class Darts {
public static int numThrows
public static int numTrials
These variables can be referenced from any method. This should fix it.
Try to remove the method prompt() it's unused, and put his block in the main method.
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
double[] cordX = randomX(numThrows);
...
I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}
I was trying to calculate each row of the file having matching answers as the exam solution as well counting each row's number of right answers using the exam solution.
I tried to calculate the number of people having the right answers as the test answers stored in the class, once reading the file and storing the file arrays into the class - after placing the file arrays into class constructor to calculate the answers, but I can't, as I get the wrong answers where the class doesn't calculate.
How do you solve this in Java, where I can calculate and store the file arrays into the class?
ExamFile3.txt:
A A A A A A B A A A B C A A A A C B D A
B D A A C A B A C D B C D A D C C B D A
B D A A C A B A C D B C D A D C C B D A
Exam solution:
B D A A C A B A C D B C D A D C C B D A
this is the class:
import java.io.*;
import java.util.*;
/*
* http://www.java-examples.com/read-char-file-using-datainputstream
*/
public class Exam {
private static boolean pass; //passed if student passes exam
private static int allRightQuestions=0; //counts number of people having full marks
private static int lessThan5score=0; //counts number of people having < 5 scores
private static int lessThan10Score=0; //counts number of people having < 10 scores
private static int totalCorrect; //number of questions being answered correctly
private static int totalIncorrect; //number of questions being answered wrongly
private static int questionsMissed[][]; //array for storing the missed question numbers
private static int passNo = 0; //number of people passing by having at least 15/20
private static int failNo = 0; //number of people failing by having less than 15/20
private static int row = 0;//for counting rows of 20 answers
private static int column = 0; //for counting letter exam answers
private static String showanswers = new String("B D A A C A B A C D B C D A D C C B D A");//the exam solution
String[] realanswers = new String[20];
private static String showresults[];
public Exam(String[] showresult, int rows)
{
// TODO Auto-generated constructor stub
showresult = new String[rows];
showresults = showresult;
row = rows;
}
public void sequentialsearch() //check the student having full marks
{
for ( row = 0; row<= showresults.length; row++)
if (showresults[row].equals(showanswers ))
{
pass = true;
passNo +=1;
allRightQuestions +=1;
}
else
{
pass = false;
}
getallright();//counts number of people having full marks
passNo();//count number of people passing
}
public int getallright()
{
return allRightQuestions;
}
public int passNo() //shows number of people who pass
{
return passNo;
}
public void checkwronganswers(String[] showresult, int row) //working out the number of wrong and right answers in test
{
boolean found = false;
int failure =0;
for ( row = 0; row <= showresult.length; row++)
for ( column = 0; column <= 20; column+=2)
{
if (showanswers.charAt(column) == showresults[row].charAt(column))
{
found = true;
totalCorrect +=1;
}
if (totalCorrect > 14 && totalCorrect <=20)
{
passNo += 1;
passNo();
}
else
{
failNo +=1;
fail();
}
if ( totalCorrect < 10)
{
lessThan10Score +=1;
lessthan10right();
failure += lessThan10Score;
}
if ( totalCorrect < 5)
{
lessThan5score +=1;
lessthan5right();
failure += lessThan5score;
}
}
failNo = failure;
fail();
}
public int fail()//number of people who failed
{
return failNo;
}
public int lessthan5right()//number of people having < 5 right answers
{
return lessThan5score;
}
public int lessthan10right()//number of people having < 5 right answers
{
return lessThan10Score;
}
public String show()
{
return showresults[0];
}
public boolean passed()
{
return pass;
}
public int totalIncorrect()
{
return totalIncorrect;
}
public int totalCorrect()
{
return totalCorrect;
}
public int questionsMissed()
{
return questionsMissed[0][0];
}
}
this is the program:
import java.io.*;
import java.util.Scanner;
public class ExamDemo {
private static Scanner kb;
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
int row = 0;
String[] showresults = new String[30]; //student answers
kb = new Scanner(System.in);
System.out.println(" Enter text:" );
String fileName = kb.nextLine();
File file = new File(fileName);
Scanner inputfile = new Scanner(file);
while( inputfile.hasNext() && row< showresults.length)
{
showresults[row] = inputfile.nextLine();
System.out.println( "row" + row + ":" + showresults[row]);
row++;
}
System.out.println( row );
showresults = new String[row];
System.out.println( "accepted" );
Exam exam = new Exam(showresults, row);
System.out.println( "reached");
System.out.println("students having all questions correct=" + exam.getallright());
System.out.println("students having passed the questions = " + exam.passNo() );
System.out.println("students having failed the questions = " + exam.fail() );
System.out.println("students having less than
5 the questions right= " + exam.lessthan5right() );
System.out.println("students having less than 10
the questions right= " + exam.lessthan10right() );
exam.show();
inputfile.close();
}
}