I am currently having an issue with a problem where my java index is out of bounds. The specific error is inside my binaryToDecimal method and is Index 32 out of bounds for length 32. I have tried to reorganize my code as in declaring the int binaryVal[] = new int[32]; as a global variable to fix the error but it does not work. How do I fix this issue?
import java.util.Scanner;
public class NumberConverter {
public static Scanner input = new Scanner(System.in);
static boolean success;
static String originalNum;
static int value = 0;
static int choice = 0;
static int intNum = 0;
static int remainder;
static char [] valueBinaryArray;
public static void main(String[] args) {
// TODO Auto-generated method stub
greeting();
getOriginalNumber();
getOutputType();
//checkValidInput();
if (value == 2 && choice == 3) {
decimalToHex();
}
else if (value == 3 && choice == 2) {
hexToDecimal();
}
else if (value == 2 && choice == 1) {
decimalToBinary();
}
else if (value == 1 && choice == 2) {
binaryToDecimal();
}
}
public static void greeting() {
System.out.println("Hello and welcome to the number systems converter");
System.out.println("Below you will be givin options as to what numbers you'd like to convert");
System.out.println("");
}
public static String getOriginalNumber() {
System.out.println("Enter a number:");
originalNum = input.next();
System.out.println("What type of number is this?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
value = input.nextInt();
return originalNum;
}
public static void getOutputType() {
System.out.println("Which number system would you like to convert to?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
choice = input.nextInt();
}
public static void checkValidInput() {
}
public static void decimalToHex() {
int intNum = Integer.valueOf(originalNum);
String str2 = "";
char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while (choice > 0) {
remainder = intNum % 16;
str2 = hex[remainder] + str2;
intNum = intNum/16;
}
}
public static void hexToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
String hexVal = "";
int digit;
while (choice > 0) {
digit = intNum % 16;
switch (digit) {
case 1:
hexVal+="F"; break;
case 2:
hexVal+="E"; break;
case 3:
hexVal+="D"; break;
case 4:
hexVal+="C"; break;
case 5:
hexVal+="B"; break;
case 6:
hexVal+="A"; break;
default:
hexVal+=Integer.toString(digit);
}
intNum = intNum/16;
}
for (counter = hexVal.length()-1; counter>=0; counter--)
System.out.print(hexVal.charAt(counter));
}
public static void decimalToBinary() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.println(binaryVal[i]);
}
}
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
}
If you have an array with 32 items the first one is index 0 and the last one is index 31. Trying to access the item at position 32 goes out of the range of the array which is why you get an array index out of bounds exception.
To see the output I would suggest maybe make the array 33 big instead of 32. It's not a proper fix but you should be able to see what it is doing.
If it still goes out of bounds I'd have a closer look at your while loop end condition.
so what is causing your error is your condition in your for statement. Currently, you are just checking if choice >= 0 the problem with this check is that it allows the for statement to go beyond the length of the array you have specified (32). In order to fix this error, you simply need to add another check to make sure the for loop cannot go beyond the length of the array you have specified. This can be done by adding this statement into your for loop: counter < binaryVal.length. This should prevent the for loop from going beyond the length of your array and you shouldn't run into any errors. Your final code for your binaryToDecimal method should look like this:
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0 && counter < binaryVal.length) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
Related
Currently programming a Clock with an alarm and met my first Dead Code error.
User input have already stored data into the following variables; aAlarm, aHour, and aMinute.. but I can't seem to get them to display into the main method. I have tried searching other problems regarding dead error and none seem to solve my problem. Below is the code, the variable 'instances' equals to 1 and will increment for the amount of times the user creates an alarm.
import java.util.*;
public class Frontend {
public static void main(String args[]) {
Backend nyet = new Backend();
Scanner scn = new Scanner(System.in);
int dec, dec2;
System.out.print("The time is: ");
System.out.println(nyet.displayClock());
//Class clock----------------------------
//Class setTime--------------------------
System.out.print("Do you wish to alter time| 1 = Yes, 0 = No:");
dec = scn.nextInt();
if (dec == 1) {
System.out.print("Input Hour:");
int hour = scn.nextInt();
if (hour < 0 || hour > 24) {
System.out.println("Sorry, there are only 24hrs in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int minute = scn.nextInt();
if (minute < 0 || minute > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
System.out.print("Input Second:");
int second = scn.nextInt();
if (second < 0 || second > 60) {
System.out.println("Sorry, there are only 60second in one minute.");
System.exit(0);
}
nyet.setTime(hour, minute, second);
scn.close();
System.out.print("The time is: ");
System.out.println(nyet.displayClock());
} //Class setTime--------------------------
//Class setAlarm-------------------------
System.out.print("Do you wish to set an alarm| 1 = Yes, 0 = No:");
int dec1 = scn.nextInt();
if (dec1 == 1) {
do {
int instc = 1;
System.out.print("Input alarm number:");
int aNum = scn.nextInt();
System.out.print("Input Hour:");
int aHr = scn.nextInt();
if (aHr < 0 || aHr > 24) {
System.out.println("Sorry, there are only 24hr in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int aMin = scn.nextInt();
if (aMin < 0 || aMin > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
System.out.print("Do you wish to set another alarm| 1 = Yes, 0 = No:");
dec2 = scn.nextInt();
if (dec2 == 1)
instc++;
nyet.setAlarm(instc, aNum, aHr, aMin);
}while (dec2 != 0);
} //Class setAlarm-------------------------
System.out.print("Show alarm| 1 = Show, 0 = Nothing:");
int z = scn.nextInt();
if (z == 1)
nyet.displayAlarm();
}
}
import java.time.OffsetTime;
public class Backend {
OffsetTime nyet = OffsetTime.now();
private int cHour, cMinute, cSecond, instances;
private int[] aAlarm, aHour, aMinute;
private boolean[] alarmOn;
public Backend() {
cHour = nyet.getHour();
cMinute = nyet.getMinute();
cSecond = nyet.getSecond();
aHour = new int[2];
aMinute = new int[2];
aAlarm = new int[2];
alarmOn = new boolean[2];
for (int i = 0; i < 2; i++) {
alarmOn[i] = !alarmOn[i];
}
}
public void setAlarm(int instncs,int aNmbr, int aHr, int aMnt) {
for (int i = 0; i < instncs; i++) {
aAlarm[i] = aNmbr;
aHour[i] = aHr;
aMinute[i] = aMnt;
instances = instncs;
}
}
public void setTime(int hr, int min, int sec) {
cHour = hr;
cMinute = min;
cSecond = sec;
}
public String displayClock() {
return String.format("%02d:%02d:%02d", cHour, cMinute, cSecond);
}
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
}
}
When I entered the code for your class Backend in my Eclipse, it showed a build error for method displayAlarm(), namely...
This method must return a result of type String
Here is the code for method displayAlarm() (exactly as it appears in your question).
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
}
It is possible that the for loop in the method will not be entered and in that case the method does not return anything. So I just added a line to get rid of the build error.
public String displayAlarm() {
for (int i = 0; i < instances; i++) { //<<< Dead Code
return String.format("%02d:%02d:%02d", aAlarm[i], aHour[i], aMinute[i]);
}
return "";
}
After adding the line, I got the dead code warning. I admit that it took me a while to discover the reason. Finally it dawned on me. The only thing in the for loop body is return. Hence there will only ever be precisely one loop iteration, so why increment i?
Guess the problem was the class had no 'static' in it.
Front end code:
public static void main(String args[]) {
int dec, dec2, amount = 0, deci0;
Backend nyet = new Backend();
Scanner scn = new Scanner(System.in);
System.out.print("Do you wish to set an alarm| 1 = Yes, 0 = No:");
int dec1 = scn.nextInt();
if (dec1 == 1) {
do {
System.out.print("Input alarm number(Stored = " + amount + "):");
int aNum = scn.nextInt();
System.out.print("Input Hour:");
int aHr = scn.nextInt();
if (aHr < 0 || aHr > 24) {
System.out.println("Sorry, there are only 24hr in one day.");
System.exit(0);
}
System.out.print("Input Minute:");
int aMin = scn.nextInt();
if (aMin < 0 || aMin > 60) {
System.out.println("Sorry, there are only 60mins in one hour.");
System.exit(0);
}
nyet.setAlarm(amount, aNum, aHr, aMin);
System.out.print("Do you wish to set another alarm(max 3)| 1 = Yes, 0 = No:");
dec2 = scn.nextInt();
if (dec2 == 1) {
amount++;
}else if (dec2 == 0) {
amount++;
nyet.setAlarm(amount, aNum, aHr, aMin);
}else {
System.out.println("The only choices are '1' and '0'.");
System.exit(0);
}
if (amount > 3) {
System.out.println("You have reached maximum storage.");
dec2 = 0;
}
}while (dec2 != 0);
}
Back end code:
public class Backend {
OffsetTime nyet = OffsetTime.now();
private int cHour, cMinute, cSecond;
private static int[] aAlarm, aHour, aMinute;
private boolean[] alarmOn;
private static int amnt;
public void setAlarm(int instncs,int aNmbr, int aHr, int aMnt) {
int i = instncs;
aAlarm[i] = aNmbr;
aHour[i] = aHr;
aMinute[i] = aMnt;
amnt = instncs;
}
public static void displayAlarm() {
for (int i = 0; i < amnt; i++) {
System.out.println("Alarm #" + aAlarm[i] + " - " + aHour[i] + ":" + aMinute[i]);
}
}
I have a program that prompts the user for a string, an initial base, and a final base. The program works fine for all digits however, when I enter in a string mixed with digits and characters it does not return the correct answer. For example, when I input the string BDRS7OPK48DAC9TDT4, original base: 30, newBase: 36, it should return ILOVEADVANCEDJAVA, but instead I get ILOVEADVANHSC6LTS. I know it's a problem with my algorithm but I cant figure out why it's returning the incorrect conversion.
import java.util.Scanner;
public class BaseConversion {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String theValue;
String result;
String newNum;
int initialBase;
int finalBase;
String[] parts = args;
if (parts.length > 0) {
theValue = parts[0];
isValidInteger(theValue);
initialBase = Integer.parseInt(parts[1]);
finalBase= Integer.parseInt(parts[2]);
isValidBase(finalBase);
}
else {
System.out.println("Please enter a value: ");
theValue = s.nextLine();
isValidInteger(theValue);
System.out.println("Please enter original base: ");
initialBase = s.nextInt();
System.out.println("Please enter new base: ");
finalBase = s.nextInt();
isValidBase(finalBase);
}
// check it
// isValidInteger(theValue, finalBase);
s.close();
newNum = convertInteger(theValue, initialBase, finalBase);
System.out.println("new number: " + newNum);
}
public static void isValidBase(int finalBase) {
if (finalBase < 2 || finalBase > 36) {
System.out.println("Error: Base must be greater than or equal to 2 & less than or equal to 36");
System.exit(1);
}
}
public static void isValidInteger(String num) {
char chDigit;
num = num.toUpperCase();
for(int d = 0; d < num.length(); d++) {
chDigit = num.charAt(d);
if (!Character.isLetter(chDigit) && !Character.isDigit(chDigit)) {
//System.out.println(chDigit);
System.out.println("Error character is not a letter or number");
System.exit(1);
}
}
}
public static String convertInteger(String theValue, int initialBase, int finalBase) {
double val = 0;
double decDigit = 0;
char chDigit;
// loop through each digit of the original number
int L = theValue.length();
for(int p = 0; p < L; p++) {
// get the digit character (0-9, A-Z)
chDigit = Character.toUpperCase(theValue.charAt(L-1-p));
// get the decimal value of our character
if(Character.isLetter(chDigit)) {
decDigit = chDigit - 'A' + 10;
}
else if (Character.isDigit(chDigit)) {
decDigit = chDigit - '0';
}
else {
System.out.println("Error d");
System.exit(1);
}
// add value to total
val += decDigit * Math.pow(initialBase, p);
}
// determine number of digits in new base
int D = 1;
for( ; Math.pow(finalBase, D) <= val; D++) {}
// use char array to hold new digits
char[] newNum = new char[D];
double pwr;
for(int p = D-1; p >= 0; p--) {
// calculate the digit for this power of newBase
pwr = Math.pow(finalBase, p);
decDigit = Math.floor(val / pwr);
val -= decDigit*pwr;
// store the digit character
if(decDigit <= 9) {
newNum[D - 1 - p] = (char) ('0' + (int)decDigit);
}
else {
newNum[D - 1 - p] = (char) ('A' + (int)(decDigit - 10));
}
}
return new String(newNum);
}
}
The algorithm is correct. Take a closer look instead at the place where you convert the input value to a decimal system and in particular at the limitations of the data type you are using.
Resources that could be helpful:
primitive data types - double point in the list
Floating point arithmetic
Question concerning similar problem
JLS - 4.2.3. Floating-Point Types, Formats, and Values
Hope this points you to the right track.
import java.math.BigInteger;
import java.util.Scanner;
public class BaseConversion {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String theValue;
String result;
String newNum;
int initialBase;
int finalBase;
String[] parts = args;
if (parts.length > 0) {
theValue = parts[0];
isValidInteger(theValue);
initialBase = Integer.parseInt(parts[1]);
finalBase= Integer.parseInt(parts[2]);
isValidBase(finalBase);
}
else {
System.out.println("Please enter a value: ");
theValue = s.nextLine();
isValidInteger(theValue);
System.out.println("Please enter original base: ");
initialBase = s.nextInt();
System.out.println("Please enter new base: ");
finalBase = s.nextInt();
isValidBase(finalBase);
}
// check it
// isValidInteger(theValue, finalBase);
s.close();
newNum = convertInteger(theValue, initialBase, finalBase);
System.out.println("new number: " + newNum);
}
public static void isValidBase(int finalBase) {
if (finalBase < 2 || finalBase > 36) {
System.out.println("Error: Base must be greater than or equal to 2 & less than or equal to 36");
System.exit(1);
}
}
public static void isValidInteger(String num) {
char chDigit;
num = num.toUpperCase();
for(int d = 0; d < num.length(); d++) {
chDigit = num.charAt(d);
if (!Character.isLetter(chDigit) && !Character.isDigit(chDigit)) {
//System.out.println(chDigit);
System.out.println("Error character is not a letter or number");
System.exit(1);
}
}
}
public static String convertInteger(String theValue, int initialBase, int finalBase) {
BigInteger bigInteger = new BigInteger(theValue,initialBase);
String value = bigInteger.toString(finalBase);
value = value.toUpperCase();
return value;
}
}
Here is the correct solution. The problem was with the data type not the algorithm. I hope this helps anyone dealing with the same type of problem.
So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));
I am creating a code that allows you to convert a binary number to a decimal number and vice versa. I have created a code that converts decimal to binary but can not workout how to implement the binary to decimal aspect.
My code for decimal to binary is below:
import java.util.*;
public class decimalToBinaryTest
{
public static void main (String [] args)
{
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
n=in.nextInt();
if(n < 0)
{
System.out.println("Not a positive interger");
}
else
{
System.out.print("Convert to binary is: ");
binaryform(n);
}
}
private static Object binaryform(int number)
{
int remainder;
if(number <= 1)
{
System.out.print(number);
return " ";
}
remainder= number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
An explanation to how the binary to decimal code work would help as well.
I have tried the method of the least significant digit*1 then the next least *1*2 then *1*2*2 but can not get it to work.
Thank you #korhner I used your number system with arrays and if statements.
This is my working code:
import java.util.*;
public class binaryToDecimalConvertor
{
public static void main (String [] args)
{
int [] positionNumsArr= {1,2,4,8,16,32,64,128};
int[] numberSplit = new int [8];
Scanner scanNum = new Scanner(System.in);
int count1=0;
int decimalValue=0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
int number = scanNum.nextInt();
while (number > 0)
{
numberSplit[count1]=( number % 10);
if(numberSplit[count1]!=1 && numberSplit[count1] !=0)
{
System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");
main(null);
}
count1++;
number = number / 10;
}
for(int count2 = 0;count2<8;count2++)
{
if(numberSplit[count2]==1)
{
decimalValue=decimalValue+positionNumsArr[count2];
}
}
System.out.print(decimalValue);
}
}
sample:
00000100
0 - 1
0 - 2
1 - 4
0 - 8
0 - 16
0 - 32
0 - 64
0 - 128
Sum values with bit 1 = 4
Good luck!
int decimal = Integer.parseInt("101101101010111", 2);
or if you prefer to doit your self
double output=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)== '1')
output=output + Math.pow(2,str.length()-1-i);
}
Here is a program which does that.
Make sure the integers you give to int and not too large.
import java.util.Scanner;
public class DecimalBinaryProgram {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true){
System.out.println("Enter integer in decimal form (or # to quit):");
String s1 = in.nextLine();
if ("#".equalsIgnoreCase(s1.trim())){
break;
}
System.out.println(decimalToBinary(s1));
System.out.println("Enter integer in binary form (or # to quit):");
String s2 = in.nextLine();
if ("#".equalsIgnoreCase(s2.trim())){
break;
}
System.out.println(binaryToDecimal(s2));
}
}
private static String decimalToBinary(String s){
int n = Integer.parseInt(s, 10);
StringBuilder sb = new StringBuilder();
if (n==0) return "0";
int d = 0;
while (n > 0){
d = n % 2;
n /= 2;
sb.append(d);
}
sb = sb.reverse();
return sb.toString();
}
private static String binaryToDecimal(String s){
int degree = 1;
int n = 0;
for (int k=s.length()-1; k>=0; k--){
n += degree * (s.charAt(k) - '0');
degree *= 2;
}
return n + "";
}
}
Of course for this method binaryToDecimal you can just do:
private static String binaryToDecimal(String s){
int n = Integer.parseInt(s, 2);
return n + "";
}
but I wanted to illustrate how you can do that explicitly.
do you want this?
private double dec(String s, int i) {
if (s.length() == 1) return s.equals("1") ? Math.pow(2, i) : 0;
else return (s.equals("1") ? Math.pow(2, i) : 0) + dec(s.substring(0, s.length() - 1), i - 1);
}
dec("101011101",0);
This is a version of a binary to decimal converter. I have used plenty of comments also. Just taught I would like to share it. Hope it is of some use to somebody.
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(); // store input from user
int[] powers = new int[16]; // contains powers of 2
int powersIndex = 0; // keep track of the index
int decimal = 0; // will contain decimals
boolean isCorrect = true; // flag if incorrect input
// populate the powers array with powers of 2
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 1 add to decimal to calculate
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex]; // calc the decimal
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false; // flag the wrong input
break; // break from loop due to wrong input
} // else if
// keeps track of which power we are on
powersIndex++; // counts from zero up to combat the loop counting down to zero
} // for
if(isCorrect) // print decimal output
System.out.println(binary + " converted to base 10 is: " + decimal);
else // print incorrect input message
System.out.println("Wrong input! It is binary... 0 and 1's like.....!");
} // main
} // BinaryToDecimal
I've written a converter that accepts both strings and ints.
public class Main {
public static void main(String[] args) {
int binInt = 10110111;
String binString = "10110111";
BinaryConverter convertedInt = new BinaryConverter(binInt);
BinaryConverter convertedString = new BinaryConverter(binString);
System.out.println("Binary as an int, to decimal: " + convertedInt.getDecimal());
System.out.println("Binary as a string, to decimal: " + convertedString.getDecimal());
}
}
public class BinaryConverter {
private final int base = 2;
private int binaryInt;
private String binaryString;
private int convertedBinaryInt;
public BinaryConverter(int b) {
binaryInt = b;
convertedBinaryInt = Integer.parseInt(Integer.toString(binaryInt), base);
}
public BinaryConverter(String s) {
binaryString = s;
convertedBinaryInt = Integer.parseInt(binaryString, base);
}
public int getDecimal() {
return convertedBinaryInt;
}
}
public static void main(String[] args)
{
System.out.print("Enter a binary number: ");
Scanner input = new Scanner(System.in);
long num = input.nextLong();
long reverseNum = 0;
int decimal = 0;
int i = 0;
while (num != 0)
{
reverseNum = reverseNum * 10;
reverseNum = num % 10;
decimal = (int) (reverseNum * Math.pow(2, i)) + decimal;
num = num / 10;
i++;
}
System.out.println(decimal);
}
I want to display the prime number required by the user. For example, if the user wants 3rd prime, I will display 5. I have the following java code.
import java.util.Scanner;
public class Prime {
private static Scanner scanner;
public static void main(String args[]) {
//get input till which prime number to be printed
// System.out.println("Enter which prime number to be printed: ");
// scanner = new Scanner(System.in);
// int limit = scanner.nextInt();
int count = 0;
int number = 2;
//System.out.println("Printing prime number from 1 to " + limit);
while(count<=3)
{
if(isPrime(number)){
count++;
// System.out.println(count);
}
number++;
}
if(count == 3)
System.out.println("10001 prime is "+number);
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
When i run it, I am not able to gett any output. Where am i going wrong?
PS: For time being, I am running the loop only until 3.
You have while(count <= 3) so when you exit the loop, count == 4.
Therefore, your if(count == 3) is never entered and nothing is printed.
Anyways the better solution would be
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(3);
int counter = 4;
while(arr.size() < inp) {
if(counter % 2 != 0 && counter%3 != 0) {
int temp = 4;
while(temp*temp <= counter) {
if(counter % temp == 0)
break;
temp ++;
}
if(temp*temp > counter) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp-1));
}
}
Here is corrected code that works.
public class Main {
public static void main(String args[]) {
//Returns fourth prime number
System.out.println(getPrimeNumber(4));
}
public static int getPrimeNumber(int order) {
int currentOrder = 1;
int currentNumber = 1;
while (currentOrder < order) {
currentNumber++;
if (isPrime(currentNumber)) currentOrder++;
}
return currentNumber;
}
public static boolean isPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
There was no need to start your counter at 0 and it mathematically wrong to start with number 2 ! Just begin with order and currentNumber initialized at 1 and if first prime number is what your user is looking for, no loop will be required !
Also, your loop condition after correct variable initialization was corrected from "<=" to "<".
That's all !