This is one of my first Java programs and I am very confused why it doesn't work. Help?
In addition, the else statement prints despite 'input' being given a correct value. Is there a structure for conditional statements that I'm missing?
package beginning;
import java.util.Scanner;
import java.lang.Math;
// VERY BROKEN
public class BinaryDecimalConverter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Number Base To Convert: 1) Binary 2) Decimal ::");
String binOrDec = sc.next();
System.out.println("Enter Number ::");
long number = sc.nextInt();
double result = 0;
if ((binOrDec.equals("1")) || (binOrDec.equals("Binary"))) {
char[] bin = ("" + number).toCharArray(); // conversion must be String >> char[]
int index = bin.length - 1;
double aggregate = 0;
for (int i = 0; i < bin.length; i++) {
aggregate = ((Math.pow(2, i)) * (bin[index])); // when using Math.pow(a, b) - a must be 'double' data type
index = index - 1;
result = result + aggregate;
}
}
if (binOrDec.equals("2") || binOrDec.equals("Decimal")) {
// decimal-binary converter, unfinished.
}
else {
System.out.println("Invalid Input");
}
System.out.println("" + number + " >> " + result);
sc.close();
}
}
your code says: if binOrDec is 2 or Decimal, do nothing, else, print invalid input. Computers do what you tell em to. I think you probably want an else in front of that line to checks for 2/Decimal.
'doesn't work' is not a great start. Help us help you:
If it does not compile, tell us the error the compiler gives you and make sure the line numbers match up or you otherwise make it possible for us to know where to look.
If it does compile, but you get an error when you run it, supply the error, as well as any input you provided that resulted in the error.
If it does compile, and run, and you get output, but it is not the output you expected, explain what you typed in to get it, what you did expect, and why.
Your bin array is of type char[]. If I supply the binary number 1010 for example, it contains 4 characters: 1, 0, 1, and 0. That's characters. ascii characters. The ascii character 1 has a large numeric value (not 1):
char c = '1';
System.out.println(1 * c);
The above prints.... 49.
So: aggregate = ((Math.pow(2, i)) * (bin[index])); is multiplying by 48 or 49 depending on whether that character is a 1 or a 0. I think you may be looking for if (bin[index] == '1') aggregate = Math.pow(2, i);.
Related
So my teacher gave me an assignment to do (will be shown below) and I tried to do it but just could not figure it out, here's the assignment:
Consider the following program that allows something like 8 + 33 + 1,345 + 137 to be entered as String input from the keyboard, A Scanner object then uses the plus signs (and any adjoining white space) as delimiters and produces the sum of these numbers (1523).
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");
String s = kb.nextLine( ); //Best to store in a String and then create a new Scanner
//object; otherwise, it can get stuck waiting for input.
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*\\+\\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}
Now modify the program as to allow either plus or minus signs
^^^THAT WAS THE ASSIGNMENT^^^
Here is my source code:
//I can't get it to work if I use subtraction and addition at the same time but they work separately
import java.util.Scanner;
public class AddEmUp {
public static void main(String[] args) {
//Here we create a String
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine();
//Now we convert the String to a scanner because we will be using Scanner methods
Scanner sc = new Scanner(s);
//Creates sum
int sum = 0;
//Does it's magic if it is addition
if (s.contains("+")) {
sc.useDelimiter("\\s*\\+\\s*");
while (sc.hasNextInt()) {
sum = sum + sc.nextInt();
}
}
//Does it's magic if it is subtraction
if (s.contains("-")) {
sc.useDelimiter("\\s*\\-\\s*");
while (sc.hasNextInt()) {
sum = sc.nextInt();
sum = sum - sc.nextInt();
}
}
//Prints the magic
System.out.println("Sum is: " + sum);
}
}
Can anybody help me solve the problem (First comment in my source code)???
I'm going to help you answer this in a way that's (hopefully) consistent with what you've learned so far. Since you haven't learned about arrays yet and are working with a Scanner with a delimiter pattern, we'll have to work around this constraint.
First, for the purposes of a school assignment, we can probably safely assume that your inputs will follow a particular pattern, along the lines of: (number)(operator)(number)(operator)(number)... and so on; additionally, you're probably not worried about input checking (making sure there are no letters/symbols/etc) or negative numbers, so we'll ignore those scenarios. Since you are only dealing with + and -, your delimiters are "\\s*\\+\\s*" and "\\s*\\-\\s*", respectively. Since these values don't change (they are constants), and (in a real program) would be used multiple times in different places, we typically store these in their own final variables:
final String PLUS = "\\s*\\+\\s*"; // by convention, constants in java are named with all caps
final String MINUS = "\\s*\\-\\s*";
Now, let's look at your sample input: 8 + 33 + 1345 - 137. How can you account for mixed operators?
int sum = 0;
Scanner sc = new Scanner(s); // s = "8 + 33 + 1345 - 137"
//What now?
You can still pull this off with one loop, but it will require some intermediate steps.
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
}
// first pass, temp = "8"
// first pass, temp = "3"
// first pass, temp = "1345 - 137" (!!!)
In the above example, temp would first be "8" (note that it's a String here), then "33" on the next pass, then "1345 - 137" on the third pass. You would typically use Integer.parseInt() to turn a String to an int, like so:
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
sum += Integer.parseInt(temp);
}
// first pass, temp = "8"
// first pass, temp = "3"
// first pass, temp = "1345 - 137", code breaks at Integer.parseInt(temp)
However, this code breaks on the third pass, because "1345 - 137" is clearly not an integer value. This is where storing the value in temp comes into play; you can use a nested loop to evaluate subtraction portions of your expression! You were on the right track with checking for + and - in the input, and here is a more appropriate spot to use it:
// start with +
sc.useDelimiter(PLUS);
while(sc.hasNext()){
String temp = sc.next();
// check if there are - signs in temp
if(temp.contains("-")){
// if there are, evaluate the subtraction expression
// for this example, temp = "1345 - 137"
Scanner sc2 = new Scanner(temp);
sc2.useDelimiter(MINUS);
int diff = sc2.nextInt(); // diff = 1345
while(sc2.hasNext()){
diff -= sc2.nextInt(); // diff = 1345 - 137 = 1208
}
sum += diff; // adds the result to the sum
} else {
sum += Integer.parseInt(temp); // there is no - sign, so skip ahead and just add to the sum
}
}
You'll notice I didn't check if the input contains a + sign at the beginning before the loop; this is because I'm assuming that even if you enter something like 1 - 5 - 9, the Scanner will still return at least that whole string when sc.next() is called, which will still go into the inner loop, and the expression will still be evaluated. I haven't used a Scanner in a very long time, so if this assumption is incorrect, you'll have to fix that.
I'm trying to create program that will ask the user to enter serial numbers in a specific format and the program will verify if the codes are valid or not.
The format should be 2 numbers, followed by a dash, 4 numbers, a dot, then 4 numbers and 2 letters (note: letters accepted are only a,b,c).
Example of valid format:
31-0001.2341ac
00-9999.0001cb
If the length of the string is longer/shorter than the format (14 characters total length) it should display invalid. Same thing, if other characters were used it will also say invalid.
This is the code that I have done so far. Im not sure how I can achieve the exact specified format. Hopefully someone can help..
import java.util.Scanner;
public class SerialCheck{
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("How many serial numbers would you like to check: ");
int length = sc.nextInt();
int valid = 0;
String[] sSerials = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++){
System.out.print ("Enter Serial " + (nCtr+1) + ": ");
sSerials[nCtr] = sc.next();
}
System.out.println();
System.out.println("The following were added: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sSerials[nCtr]);
}
System.out.println();
for(int nCtr = 0; nCtr < length; nCtr++){
for (int x = 0; x < sSerials[nCtr].length(); x++){
char c = sSerials[nCtr].charAt(x);
if((sSerials[nCtr].charAt(x)!='a') ||
(sSerials[nCtr].charAt(x)!='b') ||
(sSerials[nCtr].charAt(x)!='c') ||
(sSerials[nCtr].charAt(x)!='-') ||
(sSerials[nCtr].charAt(x)!='.')){
valid--;
}
else{
valid++;
}
}
if (valid < 0 && sSerials[nCtr].length() != 14){
System.out.println("The address is invalid.");
}
else{
System.out.println("The address is valid.");
}
}
}
}
I frequently post answers saying "don't use regular expressions". But in this case: use regular expressions. They are the right tool for this job.
boolean isValid = sSerials[nCtr].matches(
"[0-9]{2}" // Match 2 digits
+ "-" // Then a dash
+ "[0-9]{4}" // Then 4 digits
+ "\\." // Then a dot (which must be escaped)
+ "[0-9]{4}" // Then 4 digits
+ "[abc]{2}" // Then 2 a, b or c.
This regex is split up simply to explain the parts of it. You can write the string literal on one line:
boolean isValid =
sSerials[nCtr].matches("[0-9]{2}-[0-9]{4}\\.[0-9]{4}[abc]{2}");
You can use some websites or utility like regexr.com which helps building you regular expression for required string(Seqial number for your product).
Then use java.util.regex package for identifying them,
The linkjava.util.regex given will expose you all the functions using which you can filter perticular type of string.
I tried searching for answers to this specific question, I could see formatting options and how to pad zeros to the left but my output cannot have decimal space designated zeros but only the zeros from the conversion result. For example if I convert 45 to binary it should display 00101101 but it omits the first two zeros, obviously, and displays 101101. If I format the output it displays extra or less zeros based on the format specifications. I am a beginner and not very good at JAVA. All help is appreciated. Here is the part of code specific to my question:
public class DecimalToBinary {
public String toBinary(int b) {
if (b==0) {
return "0";
}
String binary = "";
while (b > 0 && b < 256) {
int rem = b % 2;
binary = rem + binary;
b = b / 2;
}
return binary;
}
//MAIN:
public static void main(String[] args) {
int Choice;
Scanner input = new Scanner(System.in);
DecimalToBinary convertD2B = new DecimalToBinary();
BinaryToDecimal convertB2D = new BinaryToDecimal();
do{
System.out.println("Hello! What would you like to do today? Please enter 1, 2, or 3 based on the following: "+"\n"+
"1. Convert Decimal to Binary"+"\n"+"2. Convert Binary to Decimal"+"\n"+"3. Exit");
Choice = input.nextInt();
if(Choice==1){
System.out.println("Enter a Decimal Number between 0 to 255: ");
int decimalNumber = input.nextInt();
if(decimalNumber<256)
{String output = convertD2B.toBinary(decimalNumber);
System.out.println("The Binary equivalent of "+decimalNumber+" is: "+output);
}
else
{System.out.println("Please start over and enter a number between 0 and 255.");}
}
You can use printf to make a formated output. This line for example produces an output of the parameter value 2 consisting of 5 digits. It will fill up with leading 0's if neccessary.
System.out.printf("%05d", 2); // output is 00002
But this will only work with decimals and not with strings. But you can use this if you calc the difference manually and put in a 0 as paramter.
System.out.printf("The Binary equivalent of "+decimalNumber+" is: %0" + (8 - output.length()) + "d%s\n", 0, output);
If output is a string then you could put some zeros in front of it to it before printing.
Just measure the length of output and prepend the "0" string to it, 8 - length times.
How do I change the code....
if (yourAnswer = numberOne + numberTwo)
{
System.out.println("That is correct!");
counter = counter + 1;
}
else
{
System.out.println("That is incorrect!");
}
This does not seem to be working for me. Can anyone help me?. The debugger is saying:
RandomNumbersProgramThree.java:21: error: incompatible types: int cannot be converted to boolean".
You cannot associate a number with a Boolean value. A boolean is true or false, not a number, however you can create a variable that indicates if a certain number represents true or false. Is this your entire program? I would like to see what "yourAnswer", "numberOne", and "numberTwo" are stored. but for now I will write a pseudo-program to explain the theory.
import java.util.*;
public class ExampleProgram
{
public static void main(String[] args)
{
System.out.println("Please enter two numbers");
Scanner answer = new Scanner (System.in);
int yourAnswer = answer.nextInt();
int numberOne = 1;
int numberTwo = 2;
if (yourAnswer == (numberOne + numberTwo))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
}
This program will ask the user to input a number, for example the number "3". It will then compare that number to the two numbers you declares, "numberOne" which equals the value of one, and "numberTwo" which equals the value of two. Therefore, in the "IF" statement it says, "If (yourAnswer == (numberOne + numberTwo))" which means that 1 + 2 = 3, if the users answer is 3, then 3 = 3 and the result will come back as true.
In the if statement, you are using an '=' sign, this type of equal sign is not a comparison '=' but is used to set a value to an variable. ie, int x = 2;
The type of equals you need is the type that is used in comparisons, which is ==. You always use == when dealing with boolean comparisons
So i have to write a program for homework where it takes a binary number and prints out its the decimal form. I've tried and and i just can't really get it. Like im printing out what it's doing every time in the loop and it looks like im getting the wrong value when i multiply the inputed data by the 2^i. If someone could help, that would be amazing
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
int value = 0;
int square_value = 0;
for (int i = 0; i < binary_number.length(); i++) {
char binary_place_holder = binary_number.charAt(i);
square_value = (int) Math.pow(2, i);
if (binary_place_holder == '1') {
value = (square_value*binary_place_holder+value);
}
System.out.println(binary_place_holder+ " " + square_value + " " + value);
}
System.out.print(binary_number + " == " + value);
}
}
The way you determine the exponent is wrong: The exponent is not i.
You need to realize that you are looking at the string from left to right side so from the highest bit.
This means the first character's exponent is 2^string_length-1.
Second character's exponent is 2^string_length-2 and so on.
Therefore as the index i becomes larger, i.e. as we are scanning the input left to right, the exponent value becomes smaller.
So the exponent is:
int exponent = binary_number.length() - 1 - i;
Note: You can of course do things in reverse and start from the end of the input string and determine the exponent that way, I just wanted to do less changes to your code.
Also, you should add a check to make sure the input is a valid binary number. You can write your own function to do it but a simpler solution is to use regex matching:
binary_number.matches("[01]+")
This will return true if the string binary_number contains only '0' and '1' characters, and false otherwise.
Applying all these changes to your code:
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
if(!binary_number.matches("[01]+")) {
System.err.println("\nPlease enter a valid binary number");
} else {
int value = 0;
for (int i = 0; i < binary_number.length(); i++) {
if (binary_number.charAt(i) == '1') {
int exponent = binary_number.length() - 1 - i;
value += (int) Math.pow(2, exponent);
}
}
System.out.print(binary_number + " == " + value);
}
}
This might be considered cheating but you could go all like
System.out.println(Integer.parseInt(binary_number, 2));