I have a program made in which users can make a self chosen x number of computations. So far so good. After the x number of computations have been made, I want to present the user all the wrong answers during the assessment. Everytime a user answers wrongly the Class "Erroranalysis" will be called. There I want to store the number of the calculation, the components of the calculation (Eg. 12 and 13 for "12+13"), the given answer and the result of the computation. Those are 5 variables. So after the chosen number of calculations have been done I want Java to put out: (Eg.)
"calculation number 3 was wrong. 13 + 18 = 31, you had: 32"
"calculation number 7 was wrong. 21 + 16 = 37, you had: 25"
etc etc
the 'add' is with a red curly stripe underneath. So I have no clue how to add this range of variables into an Array. And also how to get them out accordingly.
import java.util.ArrayList;
public class Erroranalysis
{
static ArrayList<Integer> mistakes = new ArrayList<Integer>();
public static void main(String[] args)
{
if (Sumup.counter <= Numberofcalculations.numcalc)
{
int[][] incorrect = { {Sumup.counter}, {Sumup.part1}, {Sumup.part2}, {Sumup.result}, {Sumup.answer} };
mistakes.add(incorrect);
}
if (Sumup.counter > Numberofcalculations.numcalc)
{
for (int i : mistakes)
System.out.println("Calculation number "+(incorrect[0]) + " was wrong: " + (incorrect[1])+ " + " +(incorrect[2]) + " = " + (incorrect[3])+", you had: "+ (incorrect[4]));
}
}
}
Looks like you declared the wrong ArrayList type. ArrayList accepts a generic parameter that determines the type of the elements in the list.
Try this:
private static ArrayList<int[][]> mistakes = new ArrayList<int[][]>();
By passing Integer, you told the compiler that this is a list of Integer objects (Integer is a wrapper class for the primitive type int). Then, inside the method, you tried to add an element of type int[][] to the list, so you got a compilation error.
Related
public class Test
{
public static int addOne(int[] numb)
{
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]+1);
int result = numb[i];
}
return (numbers.length);
}
}
Main:
public class Main
{
public static void main(String[] args)
{
int[] numO = {2,2,4,4,6};
System.out.println(Test.addOne(numO)); /
}
}
Output:
3,3,5,5,7,5
I was trying out arrays in java as I am starting to learn arrays, I set five numbers in the array and using a for loop, wanted to add the numbers in the array by 1, e.g. Array containing (1,2,3) would be (2,3,4) and outputting the total number 9, instead of 2,3,4 and a random number. How can I achieve this?
You are never actually changing the value contained within the numb array, what you are doing is taking the existing value and adding outputting it with 1 added to it
System.out.println(numb[i] + 1);
To change the value you must increment the value outside
numb[i]++;
System.out.println(numb[i]);
That should solve your problem of not retaining the changed value in the array. However there is another error that I can see that would prevent you from outputting the correct result value. By doing result + numb[i]; you are preforming an operation but not setting the result variable equal to anything. To set it add to the value it already contains you would do result = result + numb[i] or more properly result += numb[i]
Hope this helps!
import java.util.Random;
import java.util.Stack;
public class Blackjack {
public static void main(String[] args) {
int cardValue; /* card value is from 2 to 11 */
Stack Player1 = new Stack();
Stack Addition = new Stack();
Random r = new Random();
int i = 2 + r.nextInt(11);
System.out.println("Welcome to Mitchell's blackjack program!");
for (int a = 1; a <= 2; a++) { /* Start's the game by assigning 2 cards each, to the players */
Player1.push(i);
}
while (!Player1.empty()) {
System.out.print("You get a " + Player1.pop());
System.out.print("and");
int sum = 0;
for (int n = 0; n < Player1.size(); n++) {
sum = sum + Player1.pop();
System.out.print("Your total is " + sum);
}
}
}
}
So I just started learning java and I'm trying to accomplish this BlackJack project But, when I try to compile using javac the output was bad operand types for binary operator '+' for the 'sum = sum + Player1.pop();'
The solution i used in the above coding was from here
Player1.pop() returns an Object because you used Stack without providing a type. and you cannot do int + Object. If you need to store ints in the Stack, just use generics and do
Stack<Integer> Player1 = new Stac<Integer>k();
Stack<Integer> Addition = new Stack<Integer>();
And your
System.out.print("Your total is " + sum);
should be outside the for otherwise you will get a temporary sum
Change Stack to Stack<Integer>.
By default, you get a stack of (unknown) Objects, and you can't add an Object to an int.
Stack takes a generic argument that determines the type of Object that the Stack will store. This in turn defines the type of Object that pop() returns. In your case you could use a numeric type e.g.
Stack Player1 = new Stack<Integer>();
Providing no type argument will result in Object being returned and int + Object is not defined, hence your error.
Others have explained this using Java generics, the new Stack() approach, which tells the compiler to only let you put Integers into the Stack, and automatically takes Integers out.
Before generics, you'd just cast whatever it was you brought out of the Stack to an Integer. As people have said, the problem is that your code doesn't know what it's getting back from the stack, so it assumes Object, and doesn't know how to add those. Casting would look like:
sum = sum + (Integer)Player1.pop();
Although using Stack will solve this problem. But I guess there are issues the way you have used loop.
Your while loop will execute only once, as you for loop will empty that stack. Not sure if that's what you want to do.
So here is the code I have right now.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
int set[] = new int[5];
set[0] = (int)(Math.random()*6)+1;
set[1] = (int)(Math.random()*6)+1;
set[2] = (int)(Math.random()*6)+1;
set[3] = (int)(Math.random()*6)+1;
set[4] = (int)(Math.random()*6)+1;
System.out.println("Your current dice: " + set[0] + " " + set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
int ask = keyboard.nextInt();
After this if the user types in let's say 1 then set[1] should change to the number zero and so it becomes x0xxx and if the user also wants the 3rd number to change then it should be x0x0x.
The x's are just the generated random numbers by the way.
How do I keep doing this? It has to be a total of utmost 5 times.
Here are the basic steps you should follow to accomplish what you want/need.
Read user input (using Scanner or something else).
Validate if the user input is a valid index for the array (this is, the input is a number with a value between 0 and 5). You can store this in a variable int x.
Change the value of the element of the array inside the index user entered to 0 (or the value you want/need). This would traduce into something like set[x] = ... (change the ... by the proper value).
The way you do one thing many times is in a loop. The key is in learning which kind of loop to use.
For things that get applied to every element, use a for-each loop. For things that need done until some condition use a while loop. For things that need done until some condition becomes false, use a do-until loop.
The thing you do is the same, that goes into the block of the loop. The thing you are "working on" changes, that is a variable which the loop will set each time it "goes through" the loop's block.
In your case
for (Die die : dice) {
die.roll();
}
where class Die looks like
public class Die {
private int value;
public Die() {
roll();
}
public void roll() {
value = (int)(Math.random()*6)+1;
}
public int getValue() {
return value;
}
}
Then, since you need "order" (first, second, third, etc...) use a data structure that can contain Objects (like your Die)
List<Die> dice = new ArrayList<>();
Arrays are nice, and you do need to know how to use them; however, there are far better ways of solving most problems by not using them.
When you really can't get around using them, use a for loop to walk each array index.
I am trying to figure out a way to separate a monetary value into quarters, dimes, nickels and pennies in the most efficient way. This is currently my code:
public class CoinReader {
private static int amount = 0;
public static void main(String[] args) {
amount = (int)(Double.parseDouble(args[0])*100);
System.out.println("Five: " + computeCoin(500));
System.out.println("one: " + computeCoin(100) );
System.out.println("Q : " + computeCoin(25) );
System.out.println("D : " + computeCoin(10) );
System.out.println("N : " + computeCoin(5) );
System.out.println("P : " + computeCoin(1) );
}
public static int computeCoin(int cointValue) {
int val = amount / cointValue;
amount -= val * cointValue;
return val;
}
}
I am currently getting an Array index out of bounds exception and I know it has something to do with the String array and the amount variable but I am trying to learn about arrays and I am trying to get this program to work. Any help would be appreciated. Thanks.
You are using args[0] and args appears to be empty.
How do you call your program ? You must have forgotten to pass a parameter.
args array is empty, there is no element with index 0. You have to pass one command line argument to your program. When running from a command line make sure you pass a numeric value as an argument like this:
java CoinReader 113.25
It runs:
javac CoinReader.java
java CoinReader 1230
Ouput
Five: 246
one: 0
Q : 0
D : 0
N : 0
P : 0
Have fun to make it work correctly :-P
EDIT:
As already mentioned by the other guys the parameter String args[] refers to the arguments you provide on the command line when you run your compiled Program. You'll get an ArrayOutOfBondsException when you provide no argument as the array will be empty then.
When I say Have fun to make it work I mean that there seems to be an error in your computeCoin method as it won't output results for P, N, D and Q. But this is beyond your initial question.
SECOND EDIT:
It not just runs. It runs perfectly fine.
java CoinReader 10.11
Output:
Five: 2
one: 0
Q : 0
D : 1
N : 0
P : 1
New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;