How to design a java program using the nextLine method? - java

Here is what my program should be like:
Java: enter a binary number.
No!
Java: Please enter a binary number.
Well maybe.
JAva:can you lease enter a binary number?
101010
Java: The binary number 101010 is 42 in base 10
However, I cant get it to repeatedly ask for the user input if the input is not valid.
Moreover, I cant use Math.pow.
Here is my codings:
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex];
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
}
Problems I'm facing:
Can't use Math.pow
java wont ask for input properly (e.g. When I enter a false input, it ask me to enter a valid input. However, when I enter one, it ignores it. And it doesnt ask until the input is valid.)
If u guys can help me, I will be extremely grateful.
Thanks in advance.

First create a method that checks whether the input string is a valid binary literal or not.
Check whether it is or not. If not, just display the prompt with the text and do a nextLine again to read further input.
Do it again if the user does not enter a valid binary string.
If the user now provides a valid one, convert it to decimal.
However you have not specified what happens otherwise i.e. if the user does not provide a valid binary literal even in the 3rd attempt.
And if possible, always break down the various components of your program into smaller pieces. Something like this :
http://ideone.com/IbcW3b
The methods that do the job are :
private static int convertToBinary(String str) { // returns a decimal representation of the binary string literal }
private static boolean isBinary(String str) { // checks of string is a valid binary number }
The code assumes you loop until the user provides a valid input.

your issue is in last else :
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
put braces.
code changes are :
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
{
decimal = decimal + powers[powersIndex];
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
binary= input.nextLine();
i=binary.length();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
}
}
Your code is having too many issues check this one as i did some changes.

Related

Reverse integer including 0's in java

I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}

How to split a string up and save it to a variable if it is valid?

I'm having some problems splitting a string that is read in from an input file, making sure it's valid, then saving it to a variable.
Let's say this is the first string:
12345 5 59.28
I would want to split the 12345, 5, and 59.28.
After verifying that they are the correct format ( 00000-99999, 0-5, 000.00 0 100.00 ), I would then assign it to a variable.
My main two obstacles are that I CANNOT use arrays in this program, so I'm not sure how to split the string. I have tried just pulling each section as an int, but that doesn't seem to work.
My other problem is that I'm not sure how to validate it. Would I be using something like this:
//Assuming I have a scanner set up and a class, method declared
//Declare variables
int numbers;
int studentID;
while(fileInput.hasNext())
{
numbers = fileInput.nextInt(); //Not sure how to pull a part of the string
}
//Used to validate that it is within the range
if(numbers < 00000 || numbers > 99999)
{
studentID = numbers;
}
I am a beginner at Java so please do excuse my confusion.
If you know what the structure of the file is, for example if it's always formatted like this:
int int double
Then you can simply callnextInt(), nextInt(), and then nextDouble() to parse the data from it that way.
Maybe something like this
do
{
num1 = scanner.nextInt();
num2 = scanner.nextInt();
num3 = scanner.nextDouble();
} while (scanner.hasNextInt());
And do that in order to collect all of your data, but you'll likely need lots of variables if you have any substantial amount of data you're reading in
Or if there's bad data sometimes with it's correct data immediately after it you could so something like this to skip over the bad one, even though it's not very pretty
do
{
if (scanner.hasNextInt())
{
num1 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num1 = scanner.nextInt();
}
if (scanner.hasNextInt())
{
num2 = scanner.nextInt();
}
else
{
scanner.next() // move past whatever bad data there was
num2 = scanner.nextInt();
}
if (scanner.hasNextDouble())
{
num3 = scanner.nextDouble();
}
else
{
scanner.next() // move past whatever bad data there was
num3 = scanner.nextDouble();
}
} while (scanner.hasNext());
I think your teachers give this assignment to practice your if-else condition or switch statement and for loop(fundamental) skills.
Here what I did, this may be not completely match with your assignment question but using this you can get complete idea and think of a way to reduce this. Hey! because of we are not here to do your assignment. you have to tackle with your problem and get familiar with those.
Try to understand these, do changes look what happen:
public static void main(String[] args) {
Scanner fileInput = new Scanner(System.in);
//Declare variables
String numbers = "";
String firstNum = "";
String secondNum = "";
String thirdNum = "";
int studentID = 0;
int secondDigit = 0;
double thirdDigit = 0;
System.out.print("Input: ");
numbers = fileInput.nextLine();
int firstIndex = 0;
int secondIndex = 0;
int thirdIndex = 0;
firstIndex = numbers.indexOf(" ");
if(firstIndex <= 4){
System.out.println("Number should be 5");
}else{
firstNum = numbers.substring(0, firstIndex);
numbers = numbers.substring(firstIndex+1);
studentID = Integer.parseInt(firstNum);
if(studentID > 0 && studentID < 99999){
System.out.println("First num: " +firstNum);
}else{
System.out.println("first digits not in a range ");
}
}
secondIndex = numbers.indexOf(" ");
if(secondIndex == 0){
System.out.println("no number");
}else{
secondNum = numbers.substring(0, secondIndex);
numbers = numbers.substring(secondIndex+1);
secondDigit = Integer.parseInt(secondNum);
if(secondDigit >= 0 && secondDigit <= 5){
System.out.println("Second num: " +secondNum);
}else{
System.out.println("second digit not in a range ");
}
}
thirdIndex = numbers.length();
if(thirdIndex < 3){
System.out.println("3 numbers should be there");
}else{
thirdNum = numbers.substring(0, thirdIndex);
thirdDigit = Double.parseDouble(thirdNum);
if(thirdDigit >= 0 && thirdDigit <= 100){
System.out.println("third num: " +thirdNum);
}else{
System.out.println("third digit not in a range ");
}
}
}
I'm not going to explain this also. You have to try, if you have any problem after tackling with this code. ask any question in comment.
Hope this will help!
Try this. Invalid formats will throw an exception during the next method call.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner("12345 5 59.28");
in.useDelimiter(" "); // reads per space
String next = in.next("\\d{5}"); // reads next 5 digits
int numbers = Integer.valueOf(next);
System.out.println(numbers);
next = in.next("\\d{1}"); // reads next 1 digit
int studentId = Integer.valueOf(next);
System.out.println(studentId);
next = in.next("\\d{2}\\.\\d{2}"); // reads next a decimal with two digits before and after point
float floatingNumbers = Float.valueOf(next);
System.out.println(floatingNumbers);
}
}
<script src="//repl.it/embed/IWzC/0.js"></script>

How to check if an int contains a letter

I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.

Creating a java program to convert decimal to binary?

I'm working on a program that will display three choices. The three are:
Converting decimal to binary
Convert binary to decimal
Exit.
If the user writes "Exit" in the choice, the system to take the number and say "Goodbye".
As of right now this is what I have.
import java.util.Scanner;
public class binary {
public String toBinary(int n) {
if (n == 0) {
return "0";
}
String binary = "";
while (n > 0) {
int rem = n % 2;
binary = rem + binary;
n = n / 2;
}
return binary;
}
public static int binaryTodecimal(int i) {
int n = 0;
for (int pow = 1; i > 0; pow *= 2, i /= 10)
n += pow * (i % 10);
return n;
}
public static void main(String[] args) {
int answer2 = 0;
String answer;
final int info = 10;
for (int i = 0; i < info; i++) {
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
if (answer.equalsIgnoreCase("3"))
System.exit(0);
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
binary decimalToBinary = new binary();
String binary = decimalToBinary.toBinary(answer2);
if (answer.equals("1"))
System.out.println("The 8-bit binary representation is: " + binary);
binary bd = new binary();
int n = bd.binaryTodecimal(answer2);
if (answer.equals("2"))
System.out.println("The decimal representation is: " + answer2);
The questions I'm having is this.
In trying to convert the number in answers2 to binary or decimal, I cannot figure out how to actually split the answer2 up for this to work. I thought of doing a loop, but not sure what else I can do. Could you by chance tell me what I need to do? I'm new in Java, still trying to learn the ropes.
In converting decimal to binary, its printing out 6-bit or another bit, I want it specifically to be 8-bit. How can I fix this? Example:
Enter your choice: 1
Enter a number: 16
The 8-bit binary representation is: 10000
You can use a switch case for list of actions to be done. A switch does an action based on the choice, you may as well design to do multiple actions. for better understanding follow this link
I have not changed an of your conversion logic but the decision process and replaced it with switch
import java.util.Scanner;
public class BinaryToDecimal {
public String toBinary(int n) {
if (n == 0) {
return "0";
}
String binary = "";
while (n > 0) {
int rem = n % 2;
binary = rem + binary;
n = n / 2;
}
return binary;
}
public int binaryTodecimal(int i) {
int n = 0;
for (int pow = 1; i > 0; pow *= 2, i /= 10)
n += pow * (i % 10);
return n;
}
public static void main(String[] args) {
int answer2 = 0;
String answer;
final int info = 10;
for (int i = 0; i < info; i++) {
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
switch (answer) {
case "1": // if the answer is one do this action
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
BinaryToDecimal decimalToBinary = new BinaryToDecimal();
String binary = decimalToBinary.toBinary(answer2);
System.out.println("The 8-bit binary representation is: " + binary);
break; // leave the switch
case "2": // if answer is 2 do the following actions
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
BinaryToDecimal bd = new BinaryToDecimal();
int n = bd.binaryTodecimal(answer2);
System.out.println("The decimal representation is: " + n);
break; // leave the switch case
case "3": // when the answer is 3
System.out.println("Goodbye");
System.exit(0);
// break; you need not use here because you have an exit call
}
}
}
}
output
==================================
Enter your choice: 1
Enter a number: 25
The 8-bit binary representation is: 11001
==================================
Enter your choice: 2
Enter a number: 11001
The decimal representation is: 25
==================================
Enter your choice: 2
Enter a number: 1000000
The decimal representation is: 64
==================================
Enter your choice: 3
Goodbye
in addition : why use static for binaryToDecimal method but not for binary. I have made both the method object level. it makes more since since you are creating an object for a choice. But creating an object for every choice is not need you can use the same object created multiple time since you have not using any member variables to get your job done, see the below code
BinaryToDecimal decimalToBinary = new BinaryToDecimal();
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
switch (answer) {
case "1":
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
String binary = decimalToBinary.toBinary(answer2);
System.out.println("The 8-bit binary representation is: " + binary);
break;
case "2":
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
int n = decimalToBinary.binaryTodecimal(answer2);
System.out.println("The decimal representation is: " + n);
break;
case "3":
System.out.println("Goodbye");
System.exit(0);
break;
}
1) In trying to convert the number in answers2 to binary or decimal, I
cannot figure out how to actually split the answer2 up for this to
work. I thought of doing a loop, but not sure what else I can do.
Could you by chance tell me what I need to do? I'm new in Java, still
trying to learn the ropes.
What do you mean "how to actually split the answer2"?
to convert from binary string to decimal i suggest you
int decimal = Integer.parseInt(binaryString, 2)
on the other side you can use
String binary = Integer.toBinaryString(decimalNumber);
2) In converting decimal to binary, its printing out 6-bit, I want it
specifically to be 8-bit. How can I fix this?
If you want 8 bit you can add enough padding 0s at the beginning of the binary string:
String binaryString = Integer.toBinaryString(10);
for(int i = 8 - binaryString.length(); i > 0; i--)
binaryString = "0" + binaryString;
Of course this is not the most efficient way, but i think it's fine
Here's how i did this program.It's completely based on recursion
import java.util.*;
class Dec_To_Bin{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.print("Enter the decimal number:>");
int n=in.nextInt();
Dec_To_Bin ob=new Dec_To_Bin();
ob.binconv(n,0);
}
public void binconv(int n,int c){
if(c>7){
return ;
}
else{
binconv(n/2,c+1);
System.out.print(n%2);
}
}
}

Reversing digits in Java. Leading and trailing zeros won't print

The problem was to reverse user entered digits. I have it working but while testing it I realized that it won't print either leading or trailing zeros.
For example if I enter 10 it only displays 1 in the result.
If I enter 0110 I get a result of 11.
Here is my code:
public class ReversingDigits {
int value;
int reverse;
public ReversingDigits() {
value = 10;
reverse = 0;
}// end constructor
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
value = input.nextInt();
if (value < 10 || value > 9999){
System.out.print("Please enter a valid 2-4 digit number: ");
value = input.nextInt();
}
while (value > 0) {
reverse *= 10;
reverse += value % 10;
value /= 10;
}
System.out.println("Reversed numbers are: " + reverse);
}
}//end class
Any ideas on how to get the zeros to print?
Thanks
Make sure you work with a String while reversing your number. It will preserve leading zeros. As you know 00001 is the same as 1 when in int representation, and so converting that to a string will remove all leading zeros.
Here's your code sample modified to read a string from the input, and only convert it to an int when you need to check the range.
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
String value = input.next();
int valueInt = Integer.parseInt(value);
if (valueInt < 10 || valueInt > 9999){
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
}
String valueReversed = new StringBuilder(value).reverse().toString();
System.out.println("Reversed numbers are: " + valueReversed);
}
Note that in your code, if a user enters the wrong range twice in a row, your program won't prompt him again. You may want to put this part of the code into a do-while loop which only exits when the input range is correct. Example
do {
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
int valueInt = Integer.parseInt(value);
} while (valueInt < 10 || valueInt > 9999);
//only get here when inputted value finally within target range.
Edit: As mentioned by #Levenal, you may also want to wrap Integer.parseInt in a try/catch block for NumberFormatException in the event the user passes in a non-numerical input.
As has been pointed out, reversing numbers you are much better off reversing a string. If you are allowed to stray away from console input, JOptionPane is quite good for simple String input, like so:
while(true){
String input = JOptionPane.showInputDialog("Please anter a number between 10 & 9999: ");
if(input == null){//If input cancelled
break; //Exit loop
} else if(input.matches("\\d{2,4}")){//Regex for at least 2 but no more than 4 numbers
System.out.println(new StringBuilder(input).reverse().toString());//Reverse
break;
}
}
Good luck!

Categories