Math.pow() not working? - java

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.

Related

Java program taking list of primes and gives as output the string of symbols to corresponding G ̈odel statement

I am trying to write a program for a coding problem for class. I was thinking of doing a while loop asking for the list of primes and the somehow comparing them to a string. Down below is my code. I know its rough. Any one pointing me in the right direction would help.
public static void godel(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a list of primes: ");
System.out.println("0 to stop loop ");
int input =0;
int count = 0;
//string 0 = int 1;
//string f = int 3;
//string -\ = int 5;
//string V = int 7;
//string \-/ = int 9;
//string ( = int 11;
//string ) = int 13;
//string /\ = int 15;
//string 3 = int 17;
//string = = int 19;
//string x = int 21;
//string y = int 23
while(true){
input = scanner.nextInt();
if (input != 0)
{
input += count;
}
else{
System.out.println("Here are your list of primes in Godel's Number");
System.out.println(count);
break;
}
} }
I assume nothing is working?
first off, you need "public static void main(String[] args)" for anything to pop up. The code you want to execute (not any of the helper functions or math, just want you want to print) should be within that statement as such
public static void main(String[] args)
{
//code you want to execute here
}
I'm not sure what the godel stuff is, also you need to import the scanner library like this at the top of the code:
import java.util.Scanner;
I don't know if you need to hear any of this, but this looks like a runner because your printing out a lot of stuff and you have a scanner. I was confused as to why there was no args statement or library but I guess you maybe just didn't include it.
I no nothing about number theory so I can't help with that part.

Write a program that will read a line of text, and will display all letters in the text along with the number of times the letter appears in the text

I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.
what I have so far is:
package as10;
import java.util.*;
public class as
{
private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();
for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();
System.out.println("Letter Frequencies: ");
countLetters(letterString);
break;
}
kbd.close();
}
}
so, basically, you want to opt out all chars if counter is 0.
In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.
Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.
Does it sound fair ? :)

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.

CommandLine Java Calculator

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]

Categories