Converting a 5 digit integer into a column - java

I have to write a program to convert a 5 digit integer such as 12345 or 00005 into a column showing each individual digit on separate lines. I am asked to use two different methods, a mathematical method and string method. While the string method has given me no problems at all I am having trouble pulling each digit out individually using a mathematical method. This is my code thus far.
import java.util.Scanner; //load scanner
public class digitseparator{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter a five-digit integer: ");
String name = in.nextLine();
double n = in.nextDouble();
double ffthdgt = Double.parseInt((double)n%10000);
double frthdgt = Double.parseInt((double)n%1000);
double thrddgt = Double.parseInt((double)n%100);
double scnddgt = Double.parseInt((double)n%10);
double frstdgt = Double.parseInt((double)n%1);
System.out.println(frstdgt);
System.out.println(scnddgt);
System.out.println(thrddgt);
System.out.println(frthdgt);
System.out.println(ffthdgt);
System.out.println("String method Solution");
char frst = name.charAt(0);
System.out.println(frst);
char scnd = name.charAt(1);
System.out.println(scnd);
char thrd = name.charAt(2);
System.out.println(thrd);
char frth = name.charAt(3);
System.out.println(frth);
char ffth = name.charAt(4);
System.out.println(ffth);
}
}

First, Double has no parseInt method. It has parseDouble, which is meant to parse a String into a double. But you already have a double.
Next, you can extract a digit by...
Dividing by a power of 10 to eliminate digits to the right of the desired digit.
Taking the remainder of dividing by 10 to extract the last digit, with the % operator.

import java.util.Scanner; //load scanner
public class digitseparator
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int arr[] = new int[5];
System.out.println("Enter a five-digit integer: ");
int d =in.nextInt();
String name = Integer.toString(d);
System.out.println(name);
for(int i=0;i<5;i++)
{
arr[i] = d%10;
d = d/10;
}
for(int k=0;k<5;k++)
{
System.out.println(arr[k]);
}
System.out.println("String method Solution");
for(int m=0;m<5;m++)
{
System.out.println(name.charAt(m));
}
}
}
Hope this is what you want

Related

How can I ignore part of an input in Java?

I need to make a program that can convert hexadecimal values to decimal. I got the program to work but I need to make my program display the same output no matter if the hexadecimal value entered contains the "0x" in front or not.
this is my code.
import java.util.Scanner;
public class Main {
public static long hex2decimal(String s){
String digits = "0123456789ABCDEF";
int val = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long decimal;
System.out.println("Please enter the hex string:");
String s = sc.next().toUpperCase();
decimal = hex2decimal(s);
System.out.println(decimal);
}
}
Why should you not using Integer.parseInt("121",16), rather custom logic for converting hex to decimal. Here 16 is radix telling number is hexadecimal and will be converted to decimal.
System.out.println(Integer.parseInt("121",16));

Java Array get digits and make number from array input

import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]

How to generate characters using ASCII values

For part of my program, I am trying to ask the user for input on generating a number of random characters. I have already done this with integers and doubles, how would I do this for characters using ASCII values? Would I use the same format as I did for generating integers (Shown in code)?
import java.util.Random;
import java.util.Scanner;
public class NewNumberCharacter {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Ask the user to enter in the command: integer, double, or character
System.out.println("What do you want to generate, integer, double, or character?");
// Prompt the user to enter a string, or command, then follow the prompts
String command = input.nextLine();
if(command.equals("character")){
System.out.println("How many characters would you like generated?");
int numcharacter = input.nextInt();
RandomDataGenerator.random(numcharacter);
}
if (command.equals("integer")){
System.out.println("What is the upper limit and lower limit of the integers you want to generate?");
int maxn1 = input.nextInt();
int minn2 = input.nextInt();
System.out.println("How many integers do you want to generate?");
int numinteger = input.nextInt();
RandomDataGenerator.random(minn2,maxn1,numinteger); //Call the method
}
if (command.equals("double")){
System.out.println("What is the upper limit and lower limit of the doubles you want to generate?");
double maxn3 = input.nextDouble();
double minn4 = input.nextDouble();
System.out.println("How many doubles do you want to generate?");
int numdouble = input.nextInt();
RandomDataGenerator.random(maxn3,minn4,numdouble);
}
}
}class RandomDataGenerator {
public static int random(int maxn1, int minn2, int numinteger){
for(int i = 0 ; i < numinteger ; i++ ) {
System.out.println(maxn1 + (int)(Math.random()* minn2));
}
return 0;
}
public static double random(double maxn3, double minn4, int numdouble){
for (int i = 0; i < numdouble; i++){
Random r = new Random();
System.out.println(minn4 + (maxn3- minn4) * r.nextDouble());
}
return 0;
}
public static String random(int numcharacter){
for (int i = 0; i < numcharacter; i++){
System.out.println();
}
return null;
}
}
UpdateV2
import java.util.Random;
import java.util.Scanner;
public class NewNumberCharacter {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Ask the user to enter in the command: integer, double, or character
System.out.println("What do you want to generate, integer, double, or character?");
// Prompt the user to enter a string, or command, then follow the prompts
String command = input.nextLine();
if(command.equals("character")){
System.out.println("Enter in an ASCII value for the character" +
"\n 33 to 47 for special characters" +
"\n 65 to 90 for uppercase letters" +
"\n 97 to 102 for lowercase letters");
int ascii1 = input.nextInt();
int ascii2 = input.nextInt();
System.out.println("How many characters would you like generated?");
int numcharacter = input.nextInt();
RandomDataGenerator.random(ascii1,ascii2,numcharacter);
}
if (command.equals("integer")){
System.out.println("What is the upper limit and lower limit of the integers you want to generate?");
int maxn1 = input.nextInt();
int minn2 = input.nextInt();
System.out.println("How many integers do you want to generate?");
int numinteger = input.nextInt();
RandomDataGenerator.random(minn2,maxn1,numinteger); //Call the method
}
if (command.equals("double")){
System.out.println("What is the upper limit and lower limit of the doubles you want to generate?");
double maxn3 = input.nextDouble();
double minn4 = input.nextDouble();
System.out.println("How many doubles do you want to generate?");
int numdouble = input.nextInt();
RandomDataGenerator.random(maxn3,minn4,numdouble);
}
}
}
class RandomDataGenerator {
public static int random(int maxn1, int minn2, int numinteger){
for(int i = 0 ; i < numinteger ; i++ ) {
System.out.println(maxn1 + (int)(Math.random()* minn2));
}
return 0;
}
public static double random(double maxn3, double minn4, int numdouble){
for (int i = 0; i < numdouble; i++){
Random r = new Random();
System.out.println(minn4 + (maxn3- minn4) * r.nextDouble());
}
return 0;
}
public static char randChar(int ascii1 , int ascii2 , int numcharacter) {
for (int i = 0; i < numcharacter; i++){
Random r = new Random();
}
return(char)(Random.nextInt(ascii1-ascii2+1) + ascii1);
}
}
You would do it in a similar way. First of all, you need to learn about characters. Lookup keywords like ASCII table and Unicode.
Then select an alphabet from which you want the random characters. Printing random Chinese characters is a bit different from printing random Latin characters. Also, printing random Latin characters depends on whether you want to print them just from the base alphabet or whether you want to include additional characters from specific scripts, i.e. German Umlauts and German sz ligature.
The following example demonstrates how to create a String of random characters for uppercase Latin characters.
private static final Random random = new Random();
public static String random(final int numChars) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < numChars; i++) {
sb.append((char) (random.nextInt(26) + 'A'));
}
return sb.toString();
}
By the way, you may want to rethink a few things about your program:
You might want to return the computed value(s) instead of printing them in the functions.
You might want to move the System.out.println() out of the functions to the caller.
You might want to not generate a new random number generator in every loop iteration. One global for yourself should be enough.
If you need a random range you can do
static final Random rand = new Random();
public static char randChar(char first, char last) {
return (char)(rand.nextInt(last-first+1) + first);
}

moving the characters in a text string a specified number of positions

I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.
public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.
It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.

Create a java program that prompt the user for a positive number and then displays each digit in reverse order on a separate line

import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
output:
Please enter a value:
789
7
8
9
How do I reverse the output? For example, when I enter the number 123, it would display 321 with each digit on a new line.
If the user is inputting values in base 10, you could instead use the modulo operator along with integer division to grab the rightmost values successively in a while loop as so:
import java.util.Scanner;
public class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int quotient = value;
int remainder = 0;
while(quotient != 0){
remainder = quotient%10;
quotient = quotient/10;
System.out.print(remainder);
}
}
}
This might be a better method that attempting to convert the int to a string and then looping through the string character by character.
Loop you printing for loop in the reverse direction:
import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = digit.length()-1; i >= 0; i--) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Edit: No reason to reverse the string itself, ie. using a Stringbuilder like the other answers say. This just adds to the runtime.
import java.util.*;
public class Francis {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Simply reverse the string before looping through it
digit = new StringBuilder(digit).reverse().toString();

Categories

Resources