Java- Array Errors - java

​
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.

Related

Calculate Dice Roll from Text Field

QUESTION:
How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll?
CLARIFIER:
I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a dice roll. Then, add up all the rolls and numbers to get a total. Much like how Roll20 does with their /roll command for an example. If !clarifying {lstThen.add("look at the Roll20 and play with the /roll command to understand it")} else if !understandStill {lstThen.add("I do not know what to say, someone else could try explaining it better...")}
Info:
I was making a Java program for Dungeons and Dragons, only to find that I have come across a problem in figuring out how to calculate the user input: I do not know how to evaluate a string such as this.
I theorize that I may need Java's eval at the end. I do know what I want to happen/have a theory on how to execute (this is more so PseudoCode than Java):
Random rand = new Random();
int i = 0;
String toEval;
String char;
String roll = txtField.getText();
while (i<roll.length) {
check if character at i position is a d, then highlight the numbers
after d until it comes to a special character/!aNumber
// so if d was found before 100, it will then highlight 100 and stop
// if the character is a symbol or the end of the string
if d appears {
char = rand.nextInt(#);
i + #'s of places;
// so when i++ occurs, it will move past whatever d# was in case
// d# was something like d100, d12, or d5291
} else {
char = roll.length[i];
}
toEval = toEval + char;
i++;
}
perform evaluation method on toEval to get a resulting number
list.add(roll + " = " + evaluated toEval);
EDIT:
With weston's help, I have honed in on what is likely needed, using a splitter with an array, it can detect certain symbols and add it into a list. However, it is my fault for not clarifying on what else was needed. The pseudocode above doesn't helpfully so this is what else I need to figure out.
roll.split("(+-/*^)");
As this part is what is also tripping me up. Should I make splits where there are numbers too? So an equation like:
String[] numbers = roll.split("(+-/*^)");
String[] symbols = roll.split("1234567890d")
// Rough idea for long way
loop statement {
loop to check for parentheses {
set operation to be done first
}
if symbol {
loop for symbol check {
perform operations
}}} // ending this since it looks like a bad way to do it...
// Better idea, originally thought up today (5/11/15)
int val[];
int re = 1;
loop {
if (list[i].containsIgnoreCase(d)) {
val[]=list[i].splitIgnoreCase("d");
list[i] = 0;
while (re <= val[0]) {
list[i] = list[i] + (rand.nextInt(val[1]) + 1);
re++;
}
}
}
// then create a string out of list[]/numbers[] and put together with
// symbols[] and use Java's evaluator for the String
wenton had it, it just seemed like it wasn't doing it for me (until I realised I wasn't specific on what I wanted) so basically to update, the string I want evaluated is (I know it's a little unorthodox, but it's to make a point; I also hope this clarifies even further of what is needed to make it work):
(3d12^d2-2)+d4(2*d4/d2)
From reading this, you may see the spots that I do not know how to perform very well... But that is why I am asking all you lovely, smart programmers out there! I hope I asked this clearly enough and thank you for your time :3
The trick with any programming problem is to break it up and write a method for each part, so below I have a method for rolling one dice, which is called by the one for rolling many.
private Random rand = new Random();
/**
* #param roll can be a multipart roll which is run and added up. e.g. d6+2-d4
*/
public int multiPartRoll(String roll) {
String[] parts = roll.split("(?=[+-])"); //split by +-, keeping them
int total = 0;
for (String partOfRoll : parts) { //roll each dice specified
total += singleRoll(partOfRoll);
}
return total;
}
/**
* #param roll can be fixed value, examples -1, +2, 15 or a dice to roll
* d6, +d20 -d100
*/
public int singleRoll(String roll) {
int di = roll.indexOf('d');
if (di == -1) //case where has no 'd'
return Integer.parseInt(roll);
int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd'
int result = rand.nextInt(diceSize) + 1; //roll the dice
if (roll.startsWith("-")) //negate if nessasary
result = -result;
return result;
}

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 to output binary search answer?

I get the error message cannot find symbol, symbol: method books(int[], int) when I try to compile the following code.
For further explanation about what I want the code to do, see below the code.
public class books {
public void main(String[] args) {
int searchValue = 0, index;
int refNum[] = new int[4]; // the array
refNum[0] = 4; //numbers to refer to (aka to find)
refNum[1] = 6;
refNum[2] = 10;
refNum[3] = 12;
refNum[4] = 14;
int input = Integer.parseInt(enterValue.getText()); //takes user's input
for (int x = 0; x < refNum.length; x++) {
refNum[x] = input; //Tells refNum value to be
}
searchValue = input;
index = books(refNum, searchValue); //"books" is underlined
if (index != -1) {
binarySearchField.setText("We found: " + index);
} else {
binarySearchField.setText("Sorry! Not Found!");
}
public static Boolean binarySearch(String [] refNum, int left, int right, String search){
//Boolean code for later
}
This program uses binary search to find values stored in array after user inputs number, if they match then the item is successfully found. User inputs desired number in 'enterNumber' which is a TextField. Now in my code )which I'm 78% sure will work if it wasn't for this one little thing) there is an all important that is underlined which shouldn't be, (I've commented beside the line to show)
Now I had thought I was suppose to put the class name there, but apparently since it is underlined that is not the case. Any ideas on what I should be putting there in it's place?
And I apologize for the question may be a bit misleading on what I'm really asking, I just wasn't sure how to word the question.
The line
index = books(refNum, searchValue);
seems to be underlined because you have no method called books that takes an int[] and an int as arguments in your books class definition.
Now I had thought I was suppose to put the class name there Why do you assume you have to put the class name there? Figure out what you are trying to do with this code and then you will understand what goes in that line (at least in pseudocode).
Also it seems like you have a method declared directly inside another method. That is not legal in java. If this is not the case, please show us correct code.
books is your class's name..that might be the reason you are getting this error. You can't call constructor like a method. Change class's name to Books or something else..or change method's name

How to calculate a arithmetic expression (String) and return the answer?

I know how to calculate easy expression without variables. But how to do, when in line we have expression with "x"?
For example
(x+1)*(x-1)
In this example program should to return: x^2 - 1
It's a non-trivial endeavor. I would strongly suggest you look at what's out there. For example Symja
You might want to look at the scripting feature of java. It seems that you can execute Javascript (or other scripting languages) from Java using this scripting engine.
You will find some examples at https://today.java.net/pub/a/today/2006/04/11/scripting-for-java-platform.html.
What you are asking for, is letting a program transform (and possibly solve) mathematical equations. This is of course possible and there are tools and certainly APIs around which do it, but it's definitely beyond hacking a java program by your own.
In case you just like to calculate the result of a given formula, then this is doable. Interestingly, you can just throw an equation at Google (e.g. (5 + 3) * (8-4)) and it will give you the result. So, why not just use it? ;-)
When we go to the interview they asking the this logical type of question. i to met the same problem. but i couldn't able to success the interview because this type of questions. Later i found the result of my own after i search in in the internet. Friends who are all want to do this..
follow this operation. i will give this full of free.
I will enter the equation as string Like.
a*b*c+d/m-x.
get this equation as string object. and use following functions.#
public void calc() throws IOException
{
String equation,store,get;
StringBuilder sb= new StringBuilder();
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter the equation");
equation= dis.readLine();
equation="%"+equation+"%";
byte[] buf= equation.getBytes();
for(int i=0;i<equation.length();i++)
{
if(buf[i]>=97&&buf[i]<=122)
{
System.out.println("Enter the value for "+(char)buf[i]);
get=dis.readLine();
sb.append(get);
}
else
sb.append((char)buf[i]);
}
store= sb.toString();
char[] buf1= new char[25];
for(int i=0;i<store.length();i++)
{
buf1[i]=store.charAt(i);
}
for(int i=0;i<buf1.length;i++)
{
no.append(buf1[i]);
}
System.out.println(no.toString());
int m,n=0;
for(int i=0;i<no.length()-1;i++)
{
if('/'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) / findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('*'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) * findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('+'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) + findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length()-1;i++)
{
if('-'==no.charAt(i))
{
leftCount=rightCount=0;
m=findLeftValue(i-1) - findRightValue(i+1);
no.replace(i-leftCount, i+rightCount+1, String.valueOf(m));
i=0;
}
}
for(int i=0;i<no.length();i++)
{
if('%'==no.charAt(i))
{
no.deleteCharAt(i);
i=0;
}
}
System.out.println(no.toString());
}
public int findLeftValue(int i)
{
StringBuilder sb= new StringBuilder();
int x=0;
while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
{
leftCount++;
sb.insert(0, no.charAt(i));
i--;
}
x=Integer.parseInt(sb.toString());
return x;
}
public int findRightValue(int i)
{
StringBuilder sb= new StringBuilder();
int x;
while(no.charAt(i)!='*'&&no.charAt(i)!='+'&&no.charAt(i)!='-'&&no.charAt(i)!='/' &&no.charAt(i)!='%')
{
rightCount++;
sb.append(no.charAt(i));
i++;
}
x=Integer.parseInt(sb.toString());
return x;
}
here may be unused variable may be there.please find and remove it.
I didn't set any preferences to the calculation. just i made up with the flow. if you change the flow the answer will be different. so, Keep in mind. and you can do the same for different operators also.
And One more thing is that, Please verify the equation before proceeding the function. because, it will not check whether the equation is correct or wrong.(a+*d++c). it is not correct equation.
The equation should be correct format.. Like a+b*c-d/x.
Enjoy ..Break the interview and get your correct job..

Very simple code for number search gives me infinite loop

I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.

Categories

Resources