Required: variable Found:value Error Java Text-Based Calculator - java

Hello Stack Overflow.
I have a problem with my code. The goal is to create a text-based calculator that reads an input file and processes the equations. The first number tells the program how many lines are there. I think I set up that part right, count is the number of lines. Here's what I got so far.
Scanner equationScan;
int count;
double a=0;
double b=0;
double calc1;
equationScan = new Scanner(new File("calculator.txt"));
count = equationScan.nextInt();
while(count > 0)
{
String line = equationScan.nextLine();
if(line.equals("sin"))
{
a = equationScan.nextDouble(); *Error shows up here. Req: variable Found: value
Math.sin(a)= calc1;
}
}
The goal is a number of 'if' statements for the program to follow. I understand that part, but I can't get past this error. The first line of the text file reads an integer and I'm trying to see the second line of the file that reads sin of a double and to calculate that and store it. Help would be greatly appreciated!

Changes are in comment.
package calculator;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class calc {
public static void main(String[] args) {
Scanner equationScan = null;
int count;
double a=0;
double b=0;
double calc1;
try { //optional: add a try catch block to catch FileNotFoundException exception
equationScan = new Scanner(new File("calculator.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count = equationScan.nextInt();
equationScan.nextLine(); //add a nextline() according to what TOM pointed
while(count > 0)
{
String line = equationScan.nextLine();
if(line.equals("sin"))
{
String value=equationScan.nextLine(); //Parse the double to a string
a=Double.parseDouble(value);
calc1 = Math.sin(a) ; //Assignment should be at the right sign of the = operator
}
}
}
}

Assignments are always in the format
variable = value;
And what you did is write the value you are calculating on the left hand side of the assignment operator =, and the variable you want to put the value in, on the right side.

Related

read lines from external file and store elements in array

I am new here so please show some patience. I am trying to read the data from an external file and store the info in 2 arrays.
The file looks like this:
0069 723.50
0085 1500.00
0091 8237.31
I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok.
My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. For that reason I read it as a String. The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same.
My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. I have tried several ways (all commented) but all fail. Please help and thanks.
Here is my code:
import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;
public class Bank {
static final int MAX_NUMBER_OF_ACCOUNTS = 50;
PrintStream out;
Bank(){
UserInterfaceFactory.enableLowResolution(true);
out = new PrintStream(System.out);
}
void readFiles(){
Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(balanceFile.hasNextLine()){
String balance_Line = balanceFile.nextLine();
Scanner accountsFile = new Scanner(balance_Line);
int account = accountsFile.nextInt(); //works
out.printf("%04d ",account);
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //does not store the values properly
int account = accountsFile.nextInt();
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = account;
}*/
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //java.util.InputMismatchException
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = accountsFile.nextInt();
//out.printf("%04d \n",accounts_array[j]);
}*/
String balance = accountsFile.nextLine(); //problem declaring balance as a double
out.printf("%s\n",balance);
/*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS]; //java.util.NoSuchElementException
for(int j=0; j < balance_array.length; j++){
accountsFile.useDelimiter(" ");
balance_array[j] = accountsFile.next();
//out.printf("%04d \n",accounts_array[j]);
}*/
}
Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(mutationsFile.hasNext()){
String mutation_Line = mutationsFile.nextLine();
Scanner mutatedAccountsFile = new Scanner(mutation_Line);
int mutated_account = mutatedAccountsFile.nextInt();
out.printf("%04d ",mutated_account);
int action = mutatedAccountsFile.nextInt(); //deposit or withdrawal
/*if (action == 1){
}else{
}*/
out.printf(" %d ",action);
/*Double amount = mutatedAccountsFile.nextDouble();
out.printf(" %5.2f ",amount);*/
String amount = mutatedAccountsFile.nextLine();
out.printf("%s\n",amount);
}
}
void start(){
new Bank();readFiles();
}
public static void main(String[] args) {
new Bank().start();
}
}
The InputMismatchException occurs because you try to read a double using the nextInt() function. To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately.
while(mutationsFile.hasNext()){
mutation_Line = mutationsFile.next();
if(mutation_Line.indexOf(".") == -1)
//token is int
else
//token is double
}
Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array.
List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
Now replace the if statements in the first snippet with this:
if(mutation_Line.indexOf(".") == -1)
intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
doubleList.add(new Double(Double.parseDouble(mutation_Line)));
In the end, you can get them into arrays:
Object[] intArr = intList.toArray(),
doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
Double.parseDouble(doubleArr[i].toString()));
OUTPUT:
0069 723.50
0085 1500.00
0091 8237.31
First off, you don't need to use 2 scanners. The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file.
If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (e.g. parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles).
Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case.
If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop.
Here's an alternative approach with the code you posted.
public class App {
static int MAX_NUMBER_OF_ACCOUNTS = 50;
static PrintStream out;
static void readFiles() {
Scanner balanceFile = null;
try {
balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (balanceFile == null)
return;
int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
int currentIndex = 0;
while (balanceFile.hasNextLine()) {
int account = balanceFile.nextInt();
double balance = balanceFile.nextDouble();
System.out.print("acc = " + account + " ");
System.out.println("bal = " + balance);
//out.printf("%04d ", account);
accounts_array[currentIndex] = account;
//out.printf("%s\n", balance);
balance_array[currentIndex] = balance;
currentIndex++;
}
balanceFile.close();
}
static void start() {
readFiles();
}
public static void main(String[] args) {
start();
}
}
Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague.
As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. The arrays are allocated prior to the while loop (note: see #progy_rock and their use of ArrayList's - may help improve your code in the long run). And finally, note the index count to move the position along in the array to which you are inserting your lines to.

Delete else statement but requires else statment

So basically I'm doing a java tutorial but in order to follow along I need to make a class file. Everything was already given to me but it gives me an error. The error is: Delete else statement or something along those lines. But when I delete it it tells me to put another else statement there.
The code is : Is this a problem with eclipse or is there something wrong with the code?
import java.io.*;
import java.text.*;
public class In {
static InputStreamReader r = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(r);
// Read a String from the standard system input
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
return "";
}
}
// Read a number as a String from the standard system input
// and return the number
public static Number getNumber() {
String numberString = getString();
try {
numberString = numberString.trim().toUpperCase();
return NumberFormat.getInstance().parse(numberString);
} catch (Exception e)
{
// if any exception occurs, just return zero
return new Integer(0);
}
}
// Read an int from the standard system input
public static int getInt() {
return getNumber().intValue();
}
// Read a long from the standard system input
public static long getLong() {
return getNumber().longValue();
}
// Read a float from the standard system input
public static float getFloat() {
return getNumber().floatValue();
}
// Read a double from the standard system input
public static double getDouble() {
return getNumber().doubleValue();
}
// Read a char from the standard system input
public static char getChar() {
String s = getString();
if (s.length() >= 1)
return s.charAt(0);
else
return’\ n’;
}
}
What is actually causing the error here is that whatever messed up marks you have around \n are not apostrophes... I have no idea what they are. After rewriting the code exactly as you did, except with apostrophes (plus using curly braces in the if and else statements because I prefer it that way), there were no errors:
public static char getChar ()
{
String s = getString();
if (s.length() >= 1){
return s.charAt(0);
}else{
return '\n';
}
}
Please, in the future, make sure to use correct indentations in your questions to make it much easier for us to read.

Consume bad data in text file java

import java.io.*;
import java.util.*;
public class DemoEx {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("BP.txt"));
int badData = 0;
int goodData = 0;
while (in.hasNext()) {
try {
int value = in.nextInt();
if (value < 0)
throw new BPIllegalValueException("value cannot be less than zero");
else goodData++;
} catch (InputMismatchException ex) {
// Consume badData
badData++;
} catch (BPIllegalValueException ex) {
badData++;
}
}
System.out.println("gooddata" + goodData);
System.out.println("baddata" + badData);
}
}
public class BPIllegalValueException extends Exception {
BPIllegalValueException(String message){
System.out.println(message);
}
}
I'm writing a program the reads a txt file and then outputs the number of pieces of "good" and "bad" data with good data being any non-negative integer number and bad data being anything else.
However, I'm not sure how to consume and move to the next piece of data if my program encounters a string.
Loop with a check on encountering the int:
if (in.hasNextInt()) {
... all
} else {
++badData();
in.next();
}
What do You mean by "consume"? You propably want to advance to another token. Reading the documentation should give You the answer:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
next() method will allow You to go to a next token...

Counting Inversions for an Array of 100,000 Integers, Why Get a Negative Output?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InversionCounter {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("src/IntegerArray.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int [] nums = new int [100000];
int i = 0;
while(scanner.hasNextInt()){
nums[i++] = scanner.nextInt();
}
System.out.println(countInversions(nums));
}
public static int countInversions(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
for (int j=i+1;j<nums.length;j++) {
if (nums[i]>nums[j]) {
count++;
}
else {continue;}
}
}
return count;
}
}
The code above reads 100,000 integers from a file and counts the inversions for this array of integers. The output is probably a very large number like 1198233847 and should definitely be positive. However, it outputs a negative one like -1887062008. The program logic is likely to be correct as I have tried other algorithms for the same purpose and got the same negative number as output. I suspect that the result is too big a positive number and as a result Java converts it to a negative one.
The max value of an int is 2,147,483,647 - what you are seeing is overflow. You should make count a long if you expect it to be so big.
source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
The worst case here is 4,999,950,000 inversions, which is bigger than int's max value (2,147,483,647). You should probably use a long to store the number.

Constructor is not initializing a Scanner object

In the following code the constructor is not initializing the numFile Scanner. I added the contents of the constructor to the main method to make it work. If I do not do this a java.lang.NullPointerException is thrown. Would someone mind explaining why? Also, do I need to throw an IOException on the constructor?
Thanks for any helpful advice.
Tony
import java.io.*;
import java.util.Scanner;
public class CountPositiveIntegers {
static Scanner numFile;
static String fileName; // the name of the file in which the integers are stored
static int number; // holds the current number being read
static int counter; // a counter used to sum the number of positive integers
public CountPositiveIntegers() throws IOException {
fileName ="D:\\Java\\Source\\numFile.dat";
System.out.println("File Name: " + fileName);
numFile = new Scanner(new FileReader(fileName));
number = 0;
counter = 0;
}
public static void main(String[] args) throws FileNotFoundException {
// numFile is not being initializing in the constructor
fileName = "D:\\Java\\Source\\numFile.dat";
numFile = new Scanner(new FileReader(fileName));
number = 0;
counter = 0;
if (numFile.hasNext()) { // check to see if there are any values in the file
while (numFile.hasNextInt()) { // reads in integers
number = numFile.nextInt();
if (number % 2 == 0 & number != 0) {
counter++;
}
}
numFile.close(); // close the file
// print to screen the number of even integers stored in the file
System.out.println("There are " + counter
+ " even numbers in this file");
} else {
System.out.println("The file is empty.");
}
System.exit(0); // cleanly exit the program
}
}
You must explicitly call the constructor to have it work. (You never create a new CountPositiveIntegers()).
In fact you use only static variables, the constructor is not called, and such an object would have no non-static fields. An example of Object Oriented programming:
public class CountPositiveIntegers {
Scanner numFile;
String fileName; // the name of the file in which the integers are stored
public CountPositiveIntegers(String fname) throws IOException {
fileName = fname;
System.out.println("File Name: " + fileName);
numFile = new Scanner(new FileReader(fileName));
}
public static void main(String[] args) throws FileNotFoundException {
try {
CountPositiveIntegers obj = new CountPositiveIntegers("D:\\Java\\Source\\numFile.dat");
int number = 0; // holds the current number being read
int counter = 0; // a counter used to sum the number of positive integers
if (obj.numFile.hasNext()) { // check to see if there are any values in the file
while (obj.numFile.hasNextInt()) { // reads in integers
number = obj.numFile.nextInt();
if (number % 2 == 0 & number != 0) {
counter++;
}
}
obj.numFile.close(); // close the file
// print to screen the number of even integers stored in the file
System.out.println("There are " + counter
+ " even numbers in this file");
} else {
System.out.println("The file is empty.");
}
System.exit(0); // cleanly exit the program
} catch (IOException ex) {
Logger.getLogger(CountPositiveIntegers.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I believe that the problem is that when your program starts up, it does not create a new instance of the class in which main is executed and instead just runs the code in main. Since your initialization code is in your constructor, it's never actually run, because you don't create an instance of the main class.
To fix this, I would strongly suggest having main create a new instance of the class that main resides in, then perform all your operations on that object, rather than making everything static and just performing the operations in main directly. Your current approach is not particularly good design.
Hope this helps!
Where is your CountPositiveIntegers class object.
You need to call your constructor explicitly otherwise a default constructor will be called by the compiler.
new CountPositiveIntegers();
The constructor will not be invoked unless you actually call it. The main method does not call the constructor implicitly because it is a static method.

Categories