This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
Good morning everyone, I'm a beginner student in java programming. So, direct to the point, I'm creating a program that can read and compile a .txt file with a click of a button.
I'm already done with the reading of the file. My problem is that my program doesn't compile the text from the first JTextArea and show the results to the second JTextArea.
I've been having this problem for four days now, I've been trying to change the code in any possible ways I can think of. Can someone enlighten me and tell me what's wrong with my code? It will surely help me a lot.
Many thanks to all.
#SuppressWarnings("IncompatibleEquals")
private void executeCodeActionPerformed(java.awt.event.ActionEvent evt) {
String loadi = "Load";
String add = "Add";
String subt = "Subt";
String mult = "Mult";
String div = "Div";
String input = "Input";
String print = "Print";
int number = 0;
String txt = textAreaCode.getText();
String split = " ";
String [] text = txt.split(split);
String word = text[0];
int num = Integer.getInteger(text[1]);
int result = num;
int result1 = 0;
Scanner scan = new Scanner(txt);
scan.nextLine();
for (int count=0;count<txt.length();count++ ) {
if (loadi.equalsIgnoreCase(word)){
result1 = num + number;
}
else if (add.equalsIgnoreCase(word)){
result1 = num + result;
}
else if (subt.equalsIgnoreCase(word)){
result1 = num - result;
}
else if (mult.equalsIgnoreCase(word)){
result1 = num * result;
}
else if (div.equalsIgnoreCase(word)){
result1 = num / result;
}
else if (print.equalsIgnoreCase(word)){
textAreaOutput.setText(String.valueOf(result1));
}
else if (input.equalsIgnoreCase(word)){
String nmbr = inputField.getText();
int nmr = Integer.parseInt(nmbr);
result1 = nmr + number;
}
}
I see a few errors in your code that might add up to not working at all. Here they are:
The variable word is never updated to the following tokens (it is set to text[0] at first then never changed). Same goes for num.
All operations act on variables num and result, then put the result into result1. So intermediate results are not carried from an operation to the next.
The "input" operation load current value from inputField, without waiting for the user to actually type something.
The main loop iterate until count reach the number of characters in the program; it should loop for the number of tokens instead.
Also, here are a few suggestions to make your code more ligible:
If you are beginning in Java, then get rid of the Scanner object, and keep only the "split on spaces" approach. I would not recommend this for real problems, but Scanner is somewhat complex to use correctly.
Wrap the splited words array into a List collection, then obtain an iterator from it. Here it is:
Iterator<String> words = Arrays.asList(txt.split("[ ]+")).iterator();
Then, write your loop as:
while (words.hasNext()) {
String command = words.next();
...
}
Move your operation mnemonics outside of the function, and mark them as final.
Read your operation arguments from inside each operation block; this is required because some operation do not receive arguments.
Well, I won't give you the code, as this is something you really have to do by yourself. Hope that helps. Good luck.
Related
This question already has answers here:
Unreachable code in Java
(2 answers)
Closed 3 years ago.
My goal is to make an String array which I'm going to send to a different method, it has to be a string array. Since I don't know how many strings are going to be entered I can't predict how many string are going to be used, I am using a arrayList. But when I try to convert the arrayList to a simple array, I got an unreachable statement error in my compiler.
I got the error here:
String[] gradic = new String[lista.size()];
This is the rest of my code:
public static main(){
Scanner in = new Scanner(System.in);
System.out.println("Enter strings (empty line to end):");
List<String> list = new ArrayList<String>();
while (true){
String x = in.nextLine();
if (x.equals(" ")) continue;
lista.add(x);
}
String[] x0 = new String[list.size()];
lista.toArray(x0);
}
I want the arrayList to turn into a String[] array.
This loop does not have any break, so the program cannot go out of it:
while (true){
String x = in.nextLine();
if (x.equals(" ")) continue;
lista.add(x);
}
Probably you meant to write:
while (true){
String x = in.nextLine();
if (x.equals(" ")) break;
lista.add(x);
}
If you're just starting with Java programming, do not use while(true), not even with an appropriate break. If you want to stop reading input when the user types something specific, test for that :
Scanner in = new Scanner(System.in);
System.out.println("Enter strings (empty line to end):");
List<String> list = new ArrayList<String>();
String input = "";
while (!input.equals(" ")) { // If this is your break condition: test for it.
input = in.nextLine();
if (!input.equals(" ")) {
list.add(input);
}
}
Does that check input twice? Yes. Is it "inefficient"? Not something you should care about, or can even meaningfully comment about in this kind of code. Is it explicit on what this code should do, to human readers? Very much so, and that's what matters for code you will be writing for a while.
You cannot have while(true) with code after the loop without a break; In general, given while([condition]) if condition evaluates to true during compile time (such as with constants) then the while loop must have a break statement of some sort if there is code after the while. If there is no code after the while, it will be fine.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make a java program that will add inputs until the total equals 100+ OR the user inputs 5 numbers. I'm also attempting to add a highest run to it that keeps track of the highest input. Currently it continues to run after 5 inputs when it's less than 100 total and my highest run doesn't work. How would I fix this?(I'm new to Java if you can tell)
import java.io.*;
public class HighScoreTest {
public static void main(String[] args) {
// input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
// constant declarations
final Integer MAX = 100;
final Integer MAX_NUMBER = 4;
// variable declarations
String sName;
Integer currentTotal;
Integer currentNumber;
Integer numbersInputed = 0;
Integer count;
Integer maxRunToDate = 0;
// we catch exceptions if some are thrown.
// an exception would be entering a string when a number is expected
try {
System.out.println("What is your name?");
// reading string from the stream
sName = reader.readLine();
currentTotal = 0;
for(count = 0; count < MAX_NUMBER; count++) {
numbersInputed += count;
}
do {
System.out.println("Please enter a number");
currentNumber = Integer.parseInt(reader.readLine());
currentTotal = currentTotal + currentNumber;
}while(currentTotal < MAX || numbersInputed == MAX_NUMBER);
if (maxRunToDate < currentTotal) {
maxRunToDate = currentTotal;
}
System.out.println(sName +", the total for this run is "+ currentTotal);
System.out.println("The highest run is "+ maxRunToDate);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
Some help to get you going:
currentRun = currentRun + currentNumber;
Simply doesn't make sense!
I assume that currentRun should count the number of runs so far. So that you can stop after the 5th round.
Thus: you should just increment that counter by for each round.
In other words: try to separate things. Step back and consider what kind of information you want to "track" and how many variables you really need to do that.
And please understand: we will not solve your assignment for you. If at all, there will be some guidance on how to make progress. But don't expect us to figure all the bugs in your code and resolve them for you.
There is several things that you need to know:
First, avoid wrap classes like Integer unless you intend to use it together with the Colection FrameWork or even Streams. If your problem is the fact that the output of the parsing is the Integer class, don't worry, for it will auto unbox. Something like this:
int currentNumber = Integer.parseInt(reader.readLine()); //Auto Unboxing
Second, why do you even have the for loop in the beginning? Remove it. If you want to initialize the numbersInputed variable just do it.
And third, if you whant to increment or decrement, you can just use ++ or `--
And check the Oracle Tutorials: https://docs.oracle.com/javase/tutorial/
I hope I have helped.
Have a nice day. :)
Hi I wanted to know how to write up a try and catch block to stop from getting the below error.
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I have this method which takes a sentence and splits it into an ArrayList. I then use that to store values into a hashmap, where index 1 is the key and the words after become the value. I use the below method to split the user input into an array.
private Scanner reader;
/**
* Create a new InputReader that reads text from the text terminal.
*/
public InputReader()
{
reader = new Scanner(System.in);
}
public ArrayList<String> getInput()
{
System.out.print("> "); // print prompt
String inputLine = reader.nextLine().trim().toLowerCase();
String[] wordArray = inputLine.split(" "); // split at spaces
// add words from array into ArrayList
ArrayList<String> words = new ArrayList<String>();
for(String word : wordArray) {
words.add(word);
}
return words;
}
}
and the below method uses the class above to detect user input. So when the user types in write they can write into a hashmap but if they press return before they type in a key and value I get the out of bounds exception. So How can i rewrite the below method to avoid this?
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
ArrayList<String> input = reader.getInput();
if(input.contains("shutdown")) {
finished = true;
}
if (input.contains("load")) {
System.out.println();
instruct.readAndFill();
System.out.println();
}
if (input.contains("write")) {
String key = input.get(1);
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
instruct.mapWrite(key, value);
}
}
instructorGoodBye();
}
Sorry if i wasn't clear enough, or if my code is not up to scratch i have only been learning java for about 2 months now.
basically if the user types in write key value on one line it is fine but if they hit return after write then the error happens.
So, fundamentally what you are missing is error checking. Your program is taking input from a user, and assuming it is valid. This is always a bad idea.
Instead, you should validate what you get from the user. One way you can do this, for your "write" block, is to make sure the elements you expect to be there, are actually there.
To start, I would rewrite your loop as follows:
while(!finished) {
List<String> input = reader.getInput();
if(input.size() == 0) {
throw new IllegalArgumentException("Must specify command, one of 'shutdown', 'load', 'write'");
}
final String command = input.remove(0).toLowerCase();
// TODO: Make sure command is one of the valid commands!
Note the changes:
Assigning to List instead of ArrayList is just a good general practice.
Checking the input to make sure it has more than zero elements
Taking the first element, since we don't want to have to do List.contains(). Consider the input garbage garbage garbage write, clearly we don't want this to invoke the "write" command, it should be considered invalid input.
Finally, we use this to rewrite the conditions on executing our commands:
if(command.equals("write")) {
// Make sure the user put the right stuff in here
// Since we removed the command from the input already, just make sure what is left is
if(input.size() <= 1) {
throw new IllegalArgumentException("Must specify correct data");
}
String key = input.remove(0);
String value = String.join(" ", input); // Java 8
instruct.mapWrite(key, value);
}
You are getting the error for below part of the code..
if (input.contains("write")) {
String key = input.get(1);// here is the problem..
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
instruct.mapWrite(key, value);
}
in the line 2 of this code snippet. you are accessing a value by using the index. Now just imagine you just enter a single word in the console. so the arraylist you will get from the getInput() method will have the size of 1. So.. in the arraylist the word will be placed on 0th position.(that is the first position) but you are accessing the value on second position.. Thats gives you a index out of bond exception..
basically the fix was simpler than throwing a new exception and using a try and catch block. All I had to do was slightly change the logic and just use and if else statement.
if (input.contains("write")) {
if(input.size() >=2) {
String key = input.get(1);
String value = "";
for(int i=2; i<input.size(); i++) {
value = value + " " + input.get(i);
}
mapWrite(key, value);
} else {
System.out.println("Please type in the key & value after write all on line");
}
}
From what I have learned from java so far, is that the best solutions are normally always normally the simplest. Thanks for all the help, everyone who commented and tried to help me basically helped me come up with the idea.
I hope that this is not a stupid question, as this is only my 5th week into JAVA and Android programming. So I'm still very new to this.
Here's my code:
public void splitData(){ //**********************PROBLEM HERE**********************
//Initialise everything to 0 to prepare for variable entry
y=0;
gender = "";
sAge = "";
sTotalC = "";
smoker = "";
sHDLC = "";
medication = "";
sSystolic = "";
//To locate the spaces in the data
for(x=0;x<toSplit.length();x++){
if (toSplit.charAt(x) == ' '){
spaceCount[y]=x;
y++;
}
}
//to put together gender
for(x=0;x<spaceCount[0];x++){
gender+= toSplit.charAt(x);
}
//to put together age
for(x=spaceCount[0]+1;x<spaceCount[1];x++){
sAge+=toSplit.charAt(x);
}
//to put together total Cholesterol
for(x=spaceCount[1]+1;x<spaceCount[2];x++){
sTotalC+=toSplit.charAt(x);
}
//to put together smoker status
for(x=spaceCount[2]+1;x<spaceCount[3];x++){
smoker+=toSplit.charAt(x);
}
//to put together HDL Cholesterol level
for(x=spaceCount[3]+1;x<spaceCount[4];x++){
sHDLC+=toSplit.charAt(x);
}
//to put together medication status
for(x=spaceCount[4]+1;x<spaceCount[5];x++){
medication+=toSplit.charAt(x);
}
//to put together Systolic BP
for(x=spaceCount[5]+1;x<=toSplit.length();x++){
sSystolic+=toSplit.charAt(x);
}
}
}
So what is there is basically my terrible attempt find all the spaces in a string, and based on the spaces, combine alphabets together from the string into different variables and display each individual new constructed words into an EditText.
Everything in this code fine, right up till i hit the button mSplit should begin to do said task and then it'll show an "Unfortunately the app has stopped working".
I have googled and poked my nose around many websites but most of them use other forms of methods to split their sentences and immediately display it, without saving it into another array or variables.
It would seem and i know that i'm probably doing it the long and stupid way as i have limited knowledge about C++ thus the reason why i attempted to do it the only way i know how.
I am open to all suggestions and comments and i thank you humbly in advance.
use the split function then put it into an string array
String what = "word word1 word2 word3";
String [] temp = what.split(" ");
temp[0] will contain "word"
temp[1] will contain "word1"
and so on...
Try this code:
String[] infoArray = info.split("\\s+");
Do the same thing for your address.
In this way you don't have to initialize your array before you know it's size and you can ignore all white spaces too. It's better to trim your string before splitting it.
if you know how many of them and have more than one space in between...
String toSplit = "aoksd oaskod ssdoks aoskdo skasdk soakd";
String[] msg = new String[6];
int a = 0;
int c = 0;
while(true)
{
a = toSplit.indexOf(" ");
if(a == -1)
{
msg[c] = toSplit;
break;
}
msg[c++] = toSplit.substring(0, a);
toSplit = toSplit.substring(a, toSplit.length()).trim();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Scanner stopping at new line
I'm new to programming and I was wondering if there is a way to identify when there is a new line in a Scanner. My method is supposed to take a Scanner of a text file and break the line if it is over 60 characters long without breaking it in the middle of a word.
The problem I'm having is since I'm going by each token my code doesn't account for lines that are less than 60 characters and appends them onto the previous line up to 60 characters.
This is the method I have created:
public static void wordWrap3(Scanner s) {
String k = "";
int length = 0;
while(s.hasNext()) {
k = s.next();
length = length + k.length() + 1;
if (length>60) {
System.out.print("\n");
length = 0;
}
System.out.print(" " + k);
}
}
This is the text I am using:
We're no strangers to love, You know the rules and so do I,
A full commitment's what Im thinking of, You wouldn't get this from any other guy.
I just wanna tell you how I'm feeling, Gotta make you understand.
Never gonna give you up, Never gonna let you down, Never gonna run around and desert you.
Never gonna make you cry, Never gonna say goodbye, Never gonna tell a lie and hurt you.
You seem to be saying that you want to word wrap each line separately. If so, the simple solution is to split the input into lines, and then create a scanner for each line and pass that to your existing wordWrap3 method.
you can try:
String fileLine = "";
while(s.hasNextLine()) {
fileLine = s.nextLine();
if(fileLine.length() > 60 )
{
while (fileLine.length() > 60)
{
String tempStr = fileLine.substring(0, 60);
int rightIdx = tempStr.lastIndexOf(' ');
String firstStr = tempStr.substring(0, rightIdx);
String secStr = fileLine.substring(rightIdx + 1, fileLine.length());
System.out.println(firstStr);
//if still it is big
if(secStr.length() > 60)
fileLine = secStr;
else
{
System.out.println(secStr);
break;
}
}
}
else
{
System.out.println(fileLine);
}
}
ofcourse it can be improved further.