In the coding I have done, I have a problem at the very end. When the program actually converts the decimal into binary form, the JOptionPane window separates each number in the binary answer. I don't know how to fix this.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class decimalToBinary {
Scanner console = new Scanner (System.in);
public static void main(String [] args){
String digit;
String wrong = ("Enter a value greater than 0");
String binary_answer;
double entered_value;
digit = JOptionPane.showInputDialog
("Enter the decimal number: ");
entered_value = Double.parseDouble(digit);
if (entered_value < 0)
JOptionPane.showMessageDialog(null, wrong, "ERROR",
JOptionPane.ERROR_MESSAGE);
else
{
binary_answer = (binaryform((int) entered_value) + ".");
JOptionPane.showMessageDialog(null, binary_answer, "Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
private static Object binaryform(int number) {
double remainder;
if (number <=1) {
JOptionPane.showMessageDialog(null, number , "Result",
JOptionPane.INFORMATION_MESSAGE);
return null;
}
remainder= number %2;
binaryform( number >> 1);
JOptionPane.showMessageDialog(null, remainder , "Result",
JOptionPane.INFORMATION_MESSAGE);
{
return " ";
}
}
}
Looking at your code, I've noticed that you're calling the binaryform() multiple times.
You should stack the result in an array or collection before showing it in a joptionpane.
make it something like this
//introduce a field variable
String remainderStr='';
private static Object binaryform(int number) {
double remainder;
//if (number <=1) {
// JOptionPane.showMessageDialog(null, number , "Result",
// JOptionPane.INFORMATION_MESSAGE);
// return null;
//}
remainder= number %2;
//append on string, to display after the conversion is done.
remainderStr =remainderStr + remainder;
binaryform( number >> 1);
//move this part to main
//JOptionPane.showMessageDialog(null, remainder , "Result",
// JOptionPane.INFORMATION_MESSAGE);
//{
// return " ";
//}
}
}
Related
I've been given a task to make some conversions from ft and in to cm. I've gotten most of this down and the conversions do work. I also want to include the statement of A negative number... or A non-digit... when I type a string, for example, or a negative number, to display said message.
The problem I am getting is that when I do type up a string or negative number, I get the output of testProgram.NegativeNumberException when I enter -9, for example. And testProgram.NonDigitNumberException, when I enter joe, for example.
I am thinking there is something wrong in the catch but not sure exactly where it won't click.
package testProgram;
import java.util.InputMismatchException;
import java.util.Scanner;
public class conversion{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double cm = -1;
while(cm == -1){
cm = convertToCentimeters(scan);
if(cm!=-1){
System.out.println("Your result = " +cm);
}
else{
System.out.println("Please enter the values again.");
}
scan.nextLine();
}
}
public static double convertToCentimeters(Scanner scan){
double centimeters = -1;
try{
double foot = getFootValue(scan);
double inch = getInchValue(scan);
double totalInches = foot * 12 + inch;
centimeters = totalInches * 2.54;
}catch(NegativeNumberException e1){
System.out.println(e1);
}
catch(NonDigitNumberException e2){
System.out.println(e2);
}
return centimeters;
}
public static double getFootValue(Scanner scan) throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the foot value: ");
double foot = scan.nextDouble();
if(foot <= 0){
throw new NegativeNumberException ("A negative foot value has been entered.");
}
return foot;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit foot value has been entered.");
}
}
public static double getInchValue(Scanner scan)throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the inch value: ");
double inch = scan.nextDouble();
if(inch <= 0){
throw new NegativeNumberException ("A negative inch value has been entered.");
}
return inch;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit inch value has been entered.");
}
}
}
Alternatively to #Scary's suggestion, you can add a constructor to your custom exceptions as -
NegativeNumberException(String str) {
System.out.println(str);
}
This shall help you print the message when you
throw new NegativeNumberException ("A n....");
import javax.swing.*;
import java.awt.*;
public class JCD {
public static void main(String[] args) {
String input, inputs;
int input1, input2;
input = JOptionPane.showInputDialog("Enter first number");
inputs = JOptionPane.showInputDialog("Enter second number");
input1 = Integer.parseInt(input);
input2 = Integer.parseInt(inputs);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}// close void
private static int findGCD(int number1, int number2) {
// base case
if (number2 == 0) {
return number1;
}// end if
return findGCD(number2, number1 % number2);
}// end static
} // close class
What can I add so that it will only accept integers? If not given an integer then it will go back to ask again.....
Put your input request in a while statement, check if it's an int, if not repeat the loop, otherwise exit. Do it for both your inputs.
Something like this
public static void main(String[] args) {
String input=null, inputs=null;
int input1 = 0, input2=0;
boolean err=true;
do{
try{
input = JOptionPane.showInputDialog("Enter first number");
input1 = Integer.parseInt(input);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
err=true;
do{
try{
inputs = JOptionPane.showInputDialog("Enter second number");
input2 = Integer.parseInt(inputs);
err=false;
}catch(NumberFormatException e){
e.printStackTrace();
}
}while(err);
JOptionPane.showMessageDialog(null, "The GCD of two numbers " + input
+ "and" + inputs + " is: " + findGCD(input1, input2));
}
Note that this solution requires you to initialize your variables when you declare them
String input = null, inputs = null;
int input1=0, input2=0;
You should try with "try and catch".
input = JOptionPane.showInputDialog("Enter first number");
inputs=JOptionPane.showInputDialog("Enter second number");
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
// establish and use the variables if the characters inserted are numbers
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, e+ "is not a number");
//display a warning to le the user know
}
You could use something like this :-
boolean inputAccepted = false;
while(!inputAccepted) {
try {
input1=Integer.parseInt(input);
input2=Integer.parseInt(inputs);
inputAccepted = true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog("Please input a number only");
}
... do stuff with good input value
}
My program is to enter 10 numbers and add them together then display the result. Then I am to divide the smaller number by the larger number and display the result. Users cannot enter characters or zero.
I am new and have been working on this for DAYS. I do not see my mistake.
Now my problem is the Variable i isn't being recognized.
I introduced an Exception (try..catch) and it wouldn't read. I tried moving things all over (I'm new, I'm guessing and seeing what does what..) I did something wrong and probably something stupidly small. I need some help and fresh eyes.
I also need to end the program when the user enters 9999. Any idea where that would go? 'Cause I'm about to break out into tears.
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
You for loop doesn't have braces around it. Only the first line below it is part of the loop.
You need braces around the contents of your for loop.
I have tried to modified the attached code snippet. Hope this might help you.
package com.so.general;
import java.util.Scanner;
public class AddNumbers
{
private static final int SIZE_OF_ARRAY = 10;
public static void main(String[] args)
{
int counter = 0;
double sumOfTenDigits = 0.0;
double[] digit = new double[SIZE_OF_ARRAY];
int listOfElements = digit.length;
System.out.print("Please Enter Ten Numbers:"+"\n");
Scanner readInputFromUser = new Scanner(System.in);
try
{
for (counter=0; counter<listOfElements; counter++)
{
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
if(digit[counter] == 0.0)
{
System.out.println("Zero is not allowed. Please try again.");
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
}
sumOfTenDigits += digit[counter];
}
}
catch(NumberFormatException numberFormatExcep)
{
System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
numberFormatExcep.printStackTrace();
System.exit(0);
}
System.out.println("Addition is: "+ sumOfTenDigits);
System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
Scanner continueWithDivide = new Scanner(System.in);
String userInput = continueWithDivide.nextLine();
closeScanner(readInputFromUser);
closeScanner(continueWithDivide);
if(readInputFromUser != null)
{
readInputFromUser.close();
}
// Always use static string literals on the left hand side.
// This prevents Null pointer exception.
if("Y".equalsIgnoreCase(userInput))
{
double[] divisionResult = new double[listOfElements/2];
for(int i=0; i<listOfElements; i+=2)
{
double result = digit[i];
if (result > digit[i+1])
{
result = result/digit[i+1];
}
else
{
result = digit[i+1]/result;
}
divisionResult[i/2] = result;
System.out.println(result);
}
}
else
{
System.out.println("You have entered "+userInput+". Terminating the program.");
System.exit(0);
}
}
/**
* Closed the scanner
* #param scanner
*/
public static void closeScanner(Scanner scanner)
{
if(scanner != null)
{ try
{
scanner.close();
}
catch(IllegalStateException illegatStateExcep)
{
System.err.println("Scanner is already closed.");
illegatStateExcep.printStackTrace();
}
}
}
Please note the below points:
Always use proper indentation.
Always match { }
Even if your if or for is having only one statement, use { }.
For example:
for (int counter=1; i<digit.length; i++)
{
System.out.print("Numbers " + i + ": ");
}
Above three points will save a lot of your time if some thing goes wrong in your program.
Use proper name for the variables and method.
Always close the IO resources after the use.
For example:
if(scanner != null)
{
scanner.close();
}
I need these lines to output when a letter is typed instead of a whole number. I am not sure how to get it to do this: I have the code and what I need posted below if you can help me solve this issue, thank you.
This is what I am getting:
Input a valid whole number: abc
Input is not a valid number
Press any key to continue . . .
This is what I need:
Input a valid whole number: **ABC**
**ABC** is not a valid number
Press any key to continue . . .
below is what i have so far:
import java.io.PrintStream;
import java.util.Scanner;
public class FinalPractice
{
public static void main(String [] args)
{
Scanner scanner = new Scanner( System.in );
PrintStream out = System.out;
out.print( "Input a valid whole number: " );
String input = scanner.next();
int number;
try {
number = Integer.parseInt(input);
} catch (Exception e) {
out.println("Input is not a valid number");
return;
}
if (number < 0) {
out.println(number + " is not a valid number");
return;
}
printDivisors(number);
}
private static void printDivisors(int x){
PrintStream out = System.out;
for (int i=1; i<x; i++) {
if (isDivisibleBy(x, i)){
out.println(x + " is divisible by " + i);
} else {
out.println(x + " is not divisible by " + i);
}
}
}
private static Boolean isDivisibleBy(int x, int divisor){
while (x > 0) {
x -= divisor;
if (x == 0){
return true;
}
}
return false;
}
}
If I'm understanding correctly, you want your error message to include what the user actually inputted.
Change
out.println("Input is not a valid number");
to
out.println (input + " is not a valid number");
This takes your variable input, merges it with the rest of the String and it will then be displayed to the output console.
This is a school project:
Objective:
Ask the user to input 2 number
A random number will be print to the user.
Must catch if input isn't Integer.
I have check online source, which i copied the code and use it.
Min + (int)(Math.random() * ((Max - Min) + 1))
The code work fine except if I input any integer less than 10. The Program will consider it as a letter and says "ERROR"
My Program:
import java.lang.StringBuffer;
import java.io.IOException;
import java.util.Random;
class RandomInput2
{
public static void main(String args[])
{
System.out.println("Programe Begins");
Random seed = new Random();
int n1 , n2, rand ;
System.out.println("What is your name?");
String InputString = GCS();
while(true)
{
try
{
System.out.println("What is your First number?");
n1 = Integer.parseInt(GCS());
System.out.println("What is your second number");
n2 = Integer.parseInt(GCS());
rand = n2+ (int)(seed.nextDouble()*((n1-n2)+1));
System.out.println(InputString+" Your number is "+rand);
}
catch(NumberFormatException NFE) //catch if integer's not number
{
System.err.println("ERROR");
System.err.println("Type in Integer only");
}
catch(Exception E) //catch General Error
{
System.err.println("ERROR");
}
;
}
}
public static String GCS() //Get Console String
{
int noMoreInput =-1; //set int
char enterKeyHit= '\n'; //set char
int InputChar;
StringBuffer InputBuffer = new StringBuffer(100);
try
{
InputChar=System.in.read();
while(InputChar != noMoreInput)
{
if((char)InputChar!=enterKeyHit)
{
InputBuffer.append((char)InputChar);
}
else
{
InputBuffer.setLength(InputBuffer.length()-1);
break;
}
InputChar = System.in.read();
}//ends while loop
}
catch(IOException IOX)
{
System.err.println(IOX);
}
return InputBuffer.toString();
}
}
Look at the GSC code -- if I enter 1 character and then hit enter, what's the length of the InputBuffer when I do hit enter?
Since you want to read a whole line, consider using an InputStreamReader to read System.in, and then a BufferedReader to wrap that reader (so that you can call readLine).