How to make cards in array? - java

public void readFile() {
while (x.hasNext()) {
try {
String name = x.next();
int magic = x.nextInt();
int cunning = x.nextInt();
int courage = x.nextInt();
int wisdom = x.nextInt();
int temper = x.nextInt();
Card card = new Card(name, magic, cunning, courage, wisdom, temper);
for(int i=0;i<cardArray.length;i++){
cardArray[card];}
} catch (Exception e) {
}
}
}
I'm just making this code reading attribute from text file. The problem is how to gather all cards in one array? I try but it's not working.

I highly advise you to go thorough the basic tutorial. See the Arrays section and read it carefully.
You should assign the card this way:
cardArray[i] = card;
Note that you're using the same Card object in the loop, you'll end up with array full of the same card. Is this what you want? If not, you should create a new instance on each iteration.
Also please note that it's not a good practice to catch an exception and do nothing with it. The least you should do is print it to the console, otherwise you might get silent errors.
More questions you should ask yourself:
Do you want to declare the variables inside the while loop?
Is it worth to make a custom class that wraps magic, wisdom and all other variables? I think your code will be more modular and readable.
The full tutorial is available here, it's really worth reading. Give it a try!

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.

Java- Array Errors

​
I'm new to Java ans struggling with Arrays. I need help with an array code. There are 20 errors but I can't seem to find them (except 7). Also, I'm new to StackOverflow so sorry for the format.
Code is:
public clas ArrayProcessing
{
public void main (String [] args)
{
int iElement = 0,
int iSmallest = 0,
int iPossible = 0;
String strElements, strSmallest, strPossibles = "";
strElements = joptionPane.showInputDialog("How many elements would you like to be included in the array?");
iElements= Integer.parseInt(strElements);
strSmallest =joptionPane.showInputDialog("What would you like the smallest number in the array to be?");
iSmallest = Integer.parseInt(strSmallest);
strPossibles = joptionPane.showInputDialog("How many possible unique numbers would you like to have?");
iPossibleS= Integer.parseInt(strPossible);
int[] intArray = int[iElement];
displayArray(intArray[0]);
loadArray(intArray, iSmallest, iPossbles)
displayArray(intArray);
}
public static void loadArray(int intArray, int iSmallest, int iPossibles)
{
for (index =0; index < intArray.length(); index++)
{
intArray[index] = iSmallest + (int) (Math.random()* iPossibles);
}
}
public void displayArray(int[] intArray)
{
String strOutput="";
for (iCounter = 0, iCounter<intArray.length, iCounter++);
{
Output += intArray[iCounter] + "";
}
jOptionPane.showMessageDialog(null, "These are the values in your array: \n" + strOutput, "Arrays", JOptionPane.INFORMATION_MESSAGE);
}
You DEFINITELY need to learn the basics. Get an IDE to display the errors. Eclipse or someone suggested BlueJ (I haven't heard of it) but it will help you. Besides showing errors, it can format your code, too. You can click on the error and it will go to the error line.
use semicolons instead of commas.
If you have a "{" following a for loop, don't use semicolon.
To use swing components (i.e. JOptionPane) you need to have a JFrame to display them in.
Indenting is important for YOU and those reading the program. Makes it a lot easier to determine scope.
In a nutshell, you have the concept of programming, but you don't have the basics and you need that first. Start off with an example of, say, JOptionPane and expand on it to include your code.
Good luck. And hang in there. We've all been where you are, but we stuck with it.

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!

How do I fix my scanner input that is null?

Hi I am new at java programming and ran into a problem on my latest project. I am making a score generator for bowling and finished the code, except when I went to test it, it said
"Exception in thread "main" java.lang.NullPointerException
at Bowling_Score.main(Bowling_Score.java:34)"
I tried everything to fix it, and looked through tons of websites, but no solutions solved my problem. It's probably something really easy to fix, but I can't seem to find the answer. The line that has the problem is the second line here.
System.out.println("Frame 1, Throw 1");
Frame1Throw1 = sc.nextInt();
This is the only way I know how to use a scanner with variables, so if there is a better way please tell me. It also may be a problem because the variable Frame1Throw1 is the first variable on the list.
The variable is correct, and my scanner's name is sc
Please be specific with your answer, because as I said, I am new at java, and am just learning the basics now. This is my first big project.
Thank You!
P.S. I use eclipse to code I don't know if that matters or not
* I got one answer, and it was helpful, but It didn't work. Here is some more of the beginning of the code which may be helpful in answering.
import java.util.Scanner;
public class Bowling_Score {
private static Scanner sc;
public static void main(String[] args) {
//All Variables
int Frame1Throw1 = 0;
int Frame1Throw2 = 0;
int Frame2Throw1 = 0;
int Frame2Throw2 = 0;
int Frame3Throw1 = 0;
int Frame3Throw2 = 0;
int Frame4Throw1 = 0;
//Then I have one variable for each throw of the game, and one for the final total score.
//Directions
System.out.println("To put in your score, put the number of pins you knocked down in the throw specified. If you get a strike, enter a 10 in the first throw of the frame and a 0 in the second throw of the frame. If you get a spare, Ener a 0 in the first throw of the frame and 10 in the second throw of the frame.");
//Frame 1
System.out.println("Frame 1, Throw 1");
Frame1Throw1 = sc.nextInt();
if (Frame1Throw1 == 10){
Frame1Throw1 = Frame1Throw1 + Frame2Throw1 + Frame2Throw2;
Frame1Throw2 = 0; }
A NullPointerException means that the object you are referencing hasn't been initialised. So in this case I imagine that your sc hasn't been created previously in your code.
Look for something like
Scanner sc;
and change it to
Scanner sc = new Scanner(System.in);
Otherwise it could be a scope problem (you created the object somewhere that can't be seen by that method) you'll need to provide more code if the first solution doesn't work.

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