JProgressBar, Syntax Error on these tokens true - java

Hey I'm having a problem with 3 lines of coding, and I still don't know what the problem is.
public class HealthBar{
int min = 0;
int max = 100;
JProgressBar PlayerHealth = new JProgressBar(min,max);
JProgressBar EnemyHealth = new JProgressBar(min,max);
PlayerHealth.setStringPainted(true);
}

You can't call this method:
PlayerHealth.setStringPainted(true);
like you're doing inside the class and not in a constructor or method. Instead, make this call in your class's constructor. And again, next time you ask a similar question, please provide all the information needed including the error message.
i.e.,
public class HealthBar {
// it's OK To declare and initialize variables here
int min = 0;
int max = 100;
JProgressBar playerHealth = new JProgressBar(min,max);
JProgressBar enemyHealth = new JProgressBar(min,max);
// but this is not valid
// playerHealth.setStringPainted(true);
// constructor
public HealthBar() {
// instead do it here!!!
playerHealth.setStringPainted(true);
}
}
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter.
Following these suggestions as well as following good code formatting practices will allow others (such as us!) to better understand your code, and more importantly, will allow your future self to better understand just what you were thinking 6 months ago when you wrote the code.

Related

Using Scanner to scan through a predefined list of strings in another class, and parse them to Ints in java

Quite a few labs have passed since my previous request for some advice and we are nearing midterms quite quickly! I am currently working on another lab right now and have ran into some slight difficulty that a little advice or guidance might help! Anyways here is whats going on!
I must have 3 classes in total:
(StationRecordMain, StationRecord, and TemperatureData)
He gave us the TemperatureData class pre-written and not able to modify it in anyway. This class holds a huge array of Strings all looking like this
"14762 20180829 89 70 80 9.6" . These are some junk number in the beginning we must throw away, the year month and day, the high temp, the low temp, avg, and difference.
This prewritten class also holds 2 methods in it, (hasNextTempRecord, getNextTempRecord).
My StationRecord class holds the following instance variables:
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
Finally, my MainStationRecord class holds the Scanner Object:
Scanner scan = new Scanner(tempdata.getNextTempRecord());
, an attempt to use the scanner to read through the predefined strings in the other class.
Anyways, I can supply more code that I have written but didnt want to flood this page with all of it, but those are the basics. I believe I am at a points where I know what I need to do, just need some guidance.
I need to use the Scanner to scan through all of those Strings on the other class (there are like 100 of them, so i'm assuming some sort of loop somewhere)
Then, I need to piece out each one of those strings and store their values in those private instance variables. Finally parsing them to ints and printing them out in the main class. That is where I am lost. Ive never used a scanner in such a way to do a preset of defined strings in a different class, moreover I have no experience on how to chop them up or parse them really.
Thus, if anyone could guide me in the right direction, It would be greatly appreciated! As I said before I can post the rest of my code I have written to make things easier if need be!
Until then thank you for looking!
I think if I understand it, You can easily do something like this: (I don't have complete code of yours, so this is just a suggestion)
class StationRecord {
private int yearMonthDay = 0;
private int max = 0;
private int min = 0;
private int avg = 0;
private double dif = 0;
public StationRecord(int yearMonthDay, int max, int min, int avg, double dif) {
this.yearMonthDay = yearMonthDay;
this.max = max;
this.min = min;
this.avg = avg;
this.dif = dif;
}
// rest of your code
}
public class Main
{
public static void main(String[] args) {
// rest of your codes
while (tempdata.hasNextTempRecord()) {
Scanner scan = new Scanner(tempdata.getNextTempRecord());
scan.next(); // read until a space and I don't save it for throw it away
new StationRecord(scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextDouble());
}
// rest of your codes
}
}
Thanks Andreas for comments too. This is what I understand and write it.

String naming convention in java

I am currently trying to make a naming convention. The idea behind this is parsing.
Lets say I obtain an xml doc. Everything can be used once, but these 2 in the code below can be submitted several times within the xml document. It could be 1, or simply 100.
This states that ItemNumber and ReceiptType will be grabbed for the first element.
ItemNumber1 = eElement.getElementsByTagName("ItemNumber").item(0).getTextContent();
ReceiptType1 = eElement.getElementsByTagName("ReceiptType").item(0).getTextContent();
This one states that it will grab the second submission if they were in their twice.
ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(1).getTextContent();
ReceiptType2 = eElement.getElementsByTagName("ReceiptType").item(1).getTextContent();
ItemNumber and ReceiptType must both be submitted together. So if there is 30 ItemNumbers, there must be 30 Receipt Types.
However now I would like to set this in an IF statement to create variables.
I was thinking something along the lines of:
int cnt = 2;
if (eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();)
**MAKE VARIABLE**
Then make a loop which adds one to count to see if their is a third or 4th. Now here comes the tricky part..I need them set to a generated variable. Example if ItemNumber 2 existed, it would set it to
String ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
I do not wish to make pre-made variable names as I don't want to code a possible 1000 variables if that 1000 were to happen.
KUDOS for anyone who can help or give tips on just small parts of this as in the naming convention etc. Thanks!
You don't know beforehand how many ItemNumbers and ReceiptTypes you'll get ? Maybe consider using two Lists (java.util.List). Here is an example.
boolean finished = ... ; // true if there is no more item to process
List<String> listItemNumbers = new ArrayList<>();
List<String> listReceiptTypes = new ArrayList<>();
int cnt = 0;
while(!finished) {
String itemNumber = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
String receiptType = eElement.getElementsByTagName("ReceiptType").item(cnt).getTextContent();
listItemNumbers.add(itemNumber);
listReceiptTypes.add(receiptType);
++cnt;
// update 'finished' (to test if there are remaining itemNumbers to process)
}
// use them :
int indexYouNeed = 32; // for example
String itemNumber = listItemNumbers.get(indexYouNeed); // index start from 0
String receiptType = listReceiptTypes.get(indexYouNeed);

Obtain the largest number in an array of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!

Custom Dice Generator

Okay so this is for homework. I don't want a complete answer, just someone to help nudge me in the right direction. I am fairly new to Java, so please take it easy :P Okay so my professor is having us do a Dice simulation program with OOP. This is just one portion of the entire problem, but it's the part I'm stuck on, so if you need more I can provide more. But the instructions say:Make a Roll function that will simulate rolling each die, and return the total
This function should only allow values between the appropriate range (i.e. if each die only has 4 faces, only numbers 1 - 4 should be allowed).
What I have so far for this particular function is this:
public double Roll()
{
for(int i = 0; i < numDice; i++)
{
double total = Math.random()*numFaces + 1;
}
return total;
I don't know where to go from here, and I don't know what really to do. This is my first programming class and it's way over my head :P So like I said, if I could just get pointed in the right direction (using dummy talk, cause I'm still having a hard time grasping this whole thing) that would be awesome. And I can provide more of the actual problem if need be.
Just noticed you used double , replace double with int or short. Look at the following tutorial.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Your also not so hot with naming conventions. Read this.
http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html
You don't need to roll for each face, only for each dice. Do this.
Please note, for this you could use shorts as well.
public int roll() {
return new Random().nextInt(6) + 1; // Returns number between 1 and 6
}
If you want to roll multiple dice you could do this.
public int roll(int amount) {
int total = 0;
for(int i = 0; i < amount; i++) {
total += new Random().nextInt(6) + 1;
}
return total;
}
You're defining total inside the for loop, which makes it invisible outside it. Also, you're overwriting it (=) instead of adding to it (+=) on each die throw.
public double Roll()
{
double total = 0;
for(int i = 0; i < numDice; i++)
{
total += Math.random()*numFaces + 1;
}
return total;
}
I would also recommend to follow Java style and rename the method roll (methods start with a lowercase letter). The return type also strikes me as odd, I would probably use int in a similar situation.
You could create a class named Die to represent a die. This fits with OOP as 'die' would be one of your nouns. Now think of what configuration and behavior a Die might have. You may wish to have a Die have a configurable number of faces, but default to 6 if it isn't specified. You also want to be able to roll a die. Lets see what we have so far. Implementation left up to the reader.
public class Die {
public Die(){
this(6);
}
public Die(int faces){
//TODO: Write a constructor that takes number faces as an argument.
}
public int roll(){
//TODO: Implement a roll for this die, considering the number of faces.
}
}
Ok, so you have the beginning of a Die class. Now you might think, wouldn't it be cool if I could group die together as Dice (a set of dice if you will).
public class Dice {
public Dice(Die... dice){
//TODO: Implement constructor that takes an array of die objects.
}
public int roll(){
//TODO: Roll all the dice, sum and return the result.
}
}
Next you might think, man wouldn't it be sweet if I could treat Dice and a single Die as a single type, I mean they both can be rolled. Let us create an interface called Rollable that specified the roll behavior and have both Dice and Die implement it.
public interface Rollable {
int roll();
}
Then go back and change the class declarations to be.
public class Die implements Rollable
and
public class Dice implements Rollable
Now code that needs to roll things only needs to worry about Rollable instead of Die or Dice
First of all, you need to declare the total outside the for-loop. Then initialize it to zero.
Then, inside the for-loop. Increase the variable.
If numFaces should be able to be different for each die, you will need to get the value for it inside the for-loop, on each iteration.
Also, you should ask yourself: Which possible values do I want for the total variable? Should it be int or double?
You need to define total outside the for loop and then do total+=… inside the loop

beginner java, help me fix my program?

I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.

Categories

Resources