CommandLine Java Calculator - java

I've just learned java but from my old experience coming from C++ I thought that I can write a commandline calculator which supports all 4 basic operators with just one line. But I am having a bit of problem.
This is my code:
import java.util.Scanner;
public class omg {
public static void main(String args[]) {
int fnum,snum,anum = 0;
String strtype; //The original calculation as string
char[] testchar; //Calculation as chararray
char currentchar; //current char in the char array for the loop
int machinecode = 0; //Operator converted to integer manually
String tempnumstr; //first and second numbers temp str to be converted int
int operatorloc = 0; //operator location when found
char[] tempnum = new char[256];
Scanner scan = new Scanner(System.in); // The scanner obviously
System.out.println("Enter The Calculation: ");
strtype = scan.nextLine();
testchar = strtype.toCharArray(); //converting to char array
for (int b = 0; b < testchar.length; b++) //operator locating
{
currentchar = testchar[b];
if (currentchar == '+') {
machinecode = 1;
operatorloc = b;
}
else if (currentchar == '-') {
machinecode = 2;
operatorloc = b;
}
else if (currentchar == '*') {
machinecode = 3;
operatorloc = b;
}
else if (currentchar == '/') {
machinecode = 4;
operatorloc = b;
}
}
for(int t = 0; t < operatorloc; t++) { //transferring the left side to char
tempnum[t] = testchar[t];
}
tempnumstr = tempnum.toString(); //converting char to string
fnum = Integer.parseInt(tempnumstr); //parsing the string to a int
for (int temp = operatorloc; temp < testchar.length; temp++) { //right side
for(int t = 0;t<(testchar.length-operatorloc);t++) {
tempnum[t] = testchar[temp];
}
}
tempnumstr = tempnum.toString(); //converting to char
snum = Integer.parseInt(tempnumstr); //converting to int
switch(machinecode) { //checking the math to be done
case 1:
anum = fnum + snum;
break;
case 2:
anum = fnum - snum;
break;
case 3:
anum = fnum * snum;
break;
case 4:
anum = fnum / snum;
}
System.out.println(anum); //printing the result
}
}
This is my code but when I run it it will ask me the calculation and then give this error.
Exception in thread "main" java.lang.NullPointerException
at omg.main(omg.java:38)
There might be a better and easier way of doing this. I would like to hear both a better way and a fix for my way. Thanks in advance

You declare:
char[] tempnum = null;
But where do you set it = to a non-null value? So any time you try to use it as if it were a fully actuated object, you'll get a NPE thrown.
Edit: there are other issues in your code including calling toString() on an array which will return array's default toString -- not what you want in that situation.
So rather than this:
tempnumstr = tempnum.toString();
You probably want something like this:
tempnumstr = new String(tempnum);
or possibly
tempnumstr = new String(tempnum).trim(); // get rid of trailing whitespace if needed
Edit 2: You appear to have two char arrays in your program, tempnum and testchar, one that you fill with chars and one you don't. What is the purpose of both of them? Consider peppering your code with some comments too so we can understand it better and better be able to help you.

Hovercraft Full Of Eels has already pointed you to the reason for the NullPointerException. In addition to that, I see quite a few things that could be improved in your code. Here's how I'd do it:
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
System.out.println("Please enter your calculation");
Scanner scanner = new Scanner(System.in);
int left = scanner.nextInt();
String op = scanner.next();
int right = scanner.nextInt();
System.out.println(compute(left, op, right));
}
private static int compute(int left, String op, int right) {
switch (op.charAt(0)) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
}
throw new IllegalArgumentException("Unknown operator:" + op);
}
}
Note that the Scanner assumes there is whitespace before and after the operator.
Example output:
Please enter your calculation
1 + 2
3
The improvements in detail:
Variables may be declared where you first use them. It is customary in Java to take advantage of that (shorter code size, no need to repeat the variable name.)
Scanner provides tokenizing in addition to reading the entire line. No need to reinvent the wheel.
char (being an integer type) can be switched on.

Your problem is this line:
tempnum[t] = testchar[t];
Which will throw a NullPointerException as you previously declared it as null: char[] tempnum = null;
You need to change it to char[] tempnum = new char[size]; which will initialise it to an empty array to hold type char. Where size is any integer.

char[] tempnum = null;
should be set to something like
char[] tempnum = new char[4];
basically it is null when used at line 38.

On line 38 you try to acces the variable tempnum which is initialized to null you have to initialize the variable tempnum like this:
tempnum = new char[n]
where n will be the length of the array

You forgot to allocate tempNum which results in a NUllPointerException when you try to use it in an array context.
char[].toString() won't do what you expect (it returns a hashcode for the array object), to create a string using the contents of the array use new String(char[]).

First of all, it error at this line: tempnum[t] = testchar[t];
Reason: tempnum have not point to any thing (null)
Fix: tempnum = testchar; or tempnum = new char[testchar.length]

Related

Math.pow() not working?

this is the code i made, can someone explain me why the output stays 0.0?
(I was trying to make a program that converts binary to decimal, and i know that this can be easily accomplished in java in other ways)
package main;
import java.util.Scanner;
public class Class1 {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int length = input.length();
double output=0.0;
String reverse = new StringBuffer(input).reverse().toString();
for (int i=0; i==length; i+=1){
switch(reverse.charAt(i)){
case '1': output = (output + (Math.pow(2, i)));break;
case '0': break;
}
}
System.out.println(output);
}
}
Unless length == 0, that for loop never executes.
You might well mean something like:
for (int i=0; i<length; i+=1){
Also, there is no need to use Math.pow(2, i) - you can use 1 << i and keep it all as an integer.

the ouptput of a function is always equal to the inital one

After getting an answer from this link, I tried to make a method that returns the oldest member from a list of arrays that contains name and age of each person.
So in the main method I added those lines:
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X);
oldest(nameStr, ages);
if(X=='b')
System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
if(X=='c')
System.out.println(X);
And I created the following method oldest():
public static void oldest(String[] str, int[] ageInt)
{
int maxAge=0;
String maxName="";
for(int i=1; i<ageInt.length;i++)
{
int temporary=ageInt[0];
if(ageInt[i]>temporary)
{
maxAge = ageInt[i];
maxName = str[i];
}
}
System.out.println("The listener "+maxName+ " is the oldest with an age "+maxAge);
}
But I am getting the same result:
the listener is the oldest with an age of 0
Any help is appreciated.
EDIT
I changed the if into switch case and still the same problem:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
switch(X){
case 'a':
//System.out.println(X);
oldest(nameStr, ages);
break;
case 'b':
System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
break;
case 'c':
System.out.println(X);
break;
}
You aren't doing the correct comparison. See corrected, commented code below.
public static void oldest(String[] str, int[] ageInt)
{
int maxAge=0;
String maxName="";
for(int i=0; i<ageInt.length;i++) // start from zero
{
if(ageInt[i]>maxAge) // compare to the current max
{
maxAge = ageInt[i];
maxName = str[i];
}
}
System.out.println("The listener "+maxName+ " is the oldest with an age "+maxAge);
}
Change
if(X=='a')
System.out.println(X);
oldest(nameStr, ages);
to
if(X=='a') {
System.out.println(X);
oldest(nameStr, ages);
}
and please stick to surround if with brackets every time.
In the event the first value of ageInt[] is the greatest value, then maxAge and maxName will never be changed, since those contents are only set in the event the value of ageInt[i] is greater than the temporary value. So instead of initializing your variables via the following.
int maxAge=0;
String maxName="";
Initialize them as such:
int maxAge = ageInt[0];
String maxName = str[0];
Furthermore, ensure that you are declaring
int temporary=ageInt[0];
Outside of the for loop, otherwise you will always be setting temporary to ageInt[0], which will produce an issue if say
ageInt[0] < ageInt[1], and
ageInt[0]< ageInt[2] < ageInt[1]
As your maxAge will be set to ageInt[2] on the its iteration through the for loop. A better way to write this to avoid such an issue would be to check against your current maxAge instead of temporary.
for(int i=1; i<ageInt.length;i++){
if(ageInt[i]>maxAge){
maxAge = ageInt[i];
maxName = str[i];
}
}

String having r & g separated by 5 characters! (Error:String index out of range error)

Given an input string,check whether the string has char 'r' & 'g' separated be exactly 5 characters.
For the following code, the error is String index out of range error.
Can't figure out whats wrong
My code for class having function that checks for pattern:
public class classb {
String s = new String();
public int match(String str){
int counter = 0;
int j;
s=str;
for(j=0;j<(s.length()-6);j++){
if(s.charAt(j)=='r' && s.charAt(j+6)=='g') {
counter=1;
break;
}
if(s.charAt(j)=='g' && s.charAt(j+6)=='r'){
counter=1;
break;
}
while(s.charAt(j)!='r' || s.charAt(j)!='g'){
if(j<(s.length()-6))
j++;
else
break;
}
}
return counter;
}
}
Main class:
import java.util.*;
public class classa
{
public static void main(String[] args)
{
String a = new String();
int count;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
a= sc.nextLine();
classb x = new classb();
count=x.match(a);
if(count==1)
System.out.println("Pattern found ");
else if(count==0)
System.out.println("Pattern not found ");
}
}
You can use a regex for this problem, r.{5}g.
The r says that the pattern starts with r, and the g says that it ends with g. The . means any character, and the {5} means that there are exactly 5 (in this case of any character).
And to implement this, you would just use the method String#matches("r.{5}g").
The root problem in your code is this:
for(j=0;j<s.length();j++){
while(s.charAt(j)!='r' || s.charAt(j)!='g')
j++;
You have a loop for j where you increase J - but inside that loop you increase j again. Below that, you use j+6 in an index and you haven't checked to see if j+6 is too long. So you're repeatedly modifying j and checking 6 characters out without ever checking to see if those are in bounds.
I'd start by stopping your for loop at s.length()-6. If an r or g sequence starts in those last spots it can't complete, so no need to check them - and then your j+6 logic will work and not blow up.

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Cannot invoke equals(char) on the primitive type char

I'm new to programming and trying to nut out a basic guessing game, but I have this error. Need some help as I've set 'guess' to char, then want to compare it to the array of chars but tried a couple of different approaches but no joy yet.
It gives me the error on the if statement at the bottom containing:
(guess.equals(wordContainer[j]))
Thanks in advance.
My code:
import java.util.Scanner;
public class GuessingGame {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
String wordArray[] = {"aardvarks", "determine", "different", "greatness", "miserable", "trappings", "valuables", "xylophone"};
double rand = Math.random() * 8;
int x = 0;
x = (int)rand;
System.out.println(x);
String word = wordArray[x];
int wordCount = word.length();
System.out.println(word);
// System.out.println(wordCount);
char wordContainer[] = new char[wordCount];
char wordHiddenContainer[] = new char[wordCount];
String input;
char guess;
System.out.print("Enter your guess(a-z): ");
input = keyboard.next();
guess = input.charAt(0);
for ( int i = 0 ; i < wordCount ; i++ ) {
wordContainer[i] = word.charAt(i);
wordHiddenContainer[i] = '*';
}
System.out.println(wordContainer);
System.out.println(wordHiddenContainer);
for (int j = 0; j < word.length(); j++ ) {
if(guess.equals(wordContainer[j])) {
wordHiddenContainer[j] = guess;
}
}
}
}
Primitives are compared with ==. If you convert the chars to the wrapper classes Character, then you can use .equals().
Either change
char guess; to Character guess;
or
if(guess.equals(wordContainer[j])) to if(guess == wordContainer[j])).
equals() is a method that is contained in the Object class and passed on through inheritance to every class that is created in java. And since it is a method, it can be invoked only by objects and not primitives.
You should compare the variable guess like this
if(guess==wordContainer[j]) {
hope it helps.

Categories