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);
}
Related
i want to get all num values and print in to (......) but i couldnt do that. can u please help me?
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int operands,num;
int q=1;
int a=0;
do
{
System.out.println("Enter the number of operands (in range 2-10):");
operands=keyboard.nextInt();
} while ((operands<2) || (operands>10));
for (int number=1; number<=operands; number++)
{
System.out.println("Enter number "+number+":");
num=keyboard.nextInt();
q=q*num;
}
System.out.print("Multiplication of numbers "+(.......)+" is: "+q);
I like FranzKnut answer but if performance is an issue, and even if it isn't, then please consider using a string builder instead.
Before the loop use
StringBuilder sb = new StringBuilder("my numbers are: ");
Inside the loop add the following code.
sb.append(num);
Then at the end of loop you have something like
System.out.println(sb.toString());
Use an additional String variable you declare before the loop:
String numbers=" ";
and add to it in the loop body:
numbers += num+" ";
then print out this string in the place of (.......)
Simply add a String into the program and concat with the new added numbers. Finally print string where you have to print.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int operands, num;
int q = 1;
int a = 0;
String s = " ";
do {
System.out.println("Enter the number of operands (in range 2-10):");
operands = keyboard.nextInt();
} while ((operands < 2) || (operands > 10));
for (int number = 0; number <= operands - 1; number++) {
System.out.println("Enter number " + number + ":");
num = keyboard.nextInt();
s = s + num;
q = q * num;
}
System.out.print("Multiplication of" + s + " numbers is: " + q);
}
ok here you got
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int operands,num;
int q=1;
int a=0;
List<Integer> numbers = new ArrayList<Integer>();
int newNumbers = 1;
do
{
System.out.println("Enter the number of operands (in range 2-10):");
operands=keyboard.nextInt();
} while ((operands<2) || (operands>10));
for (int number=1; number<=operands; number++)
{
System.out.println("Enter number "+number+":");
num=keyboard.nextInt();
q=q*num;
numbers.add(num);
}
StringBuilder newTextNumber = new StringBuilder("");
for(Integer s: numbers){
newTextNumber.append(s).append(" ");
newNumbers *= s;
}
System.out.print("Multiplication of numbers "+newTextNumber+" is: "+newNumbers);
}
}
Enter the number of operands (in range 2-10):
3
Enter number 1:
20
Enter number 2:
30
Enter number 3:
10
Multiplication of numbers 20 30 10 is: 6000
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]
Scanner scan = new Scanner(System.in);
int amount = 0;
int input = 0;
int[] numbers = new int [amount];
for(int i = 0; i<1; i++ )
{
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
if (amount==amount)
{
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
input = scan.nextInt();
input = input + input;
}
}
}
double average = input/amount;
System.out.println(average);
}
}
I want to every number the user inputs, but how would I go about that?
For example, if the input is a 2 then a 3 then a 4 how do i take those and print them out in the next line while stating their averages.
There are a few problems with the code as you have written it.
if (amount == amount) is the same as saying if (true), so you might as well remove it.
You are doubling your input for no particular reason.
You are trying to build an array to store the amount before knowing how big it needs to be.
Your outer for loop is looping exactly once, so you do not need that either.
Here is a working and simplified revision of your code.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
// Now that we know the amount, we can build an array to hold that
// amount.
int[] numbers = new int [amount];
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
numbers[x] = scan.nextInt();
total += numbers[x];
}
double average = total * 1.0 /amount; // Prevent integer division
System.out.println(average);
}
}
Update: The code above will compute the average of the numbers that the user has provide.
The OP seems to hint that he wants the proportion of each input instead. Here is a modification using HashMap to accomplish that.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amount = 0;
int total = 0;
// Create a Map to get the count of each input.
Map<Integer,Integer> counts = new TreeMap<Integer,Integer>();
System.out.println("How many numbers do you plan to enter?");
amount = scan.nextInt();
for(int x = 0; x<amount; x++)
{
System.out.println("Enter a number");
int input = scan.nextInt();
if (counts.containsKey(input)) counts.put(input, counts.get(input) + 1);
else counts.put(input,1);
}
// Print out the percentage of each input
for (Integer key : counts.keySet())
System.out.printf("%d\t%.2f%%\n", key, counts.get(key) * 100.0 / amount);
}
}
You can adapt your code to not even have to ask how many numbers you plan to enter.
import java.util.Scanner;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
System.out.println("Please enter some numbers, n to terminate: ");
while(kb.hasNextInt())
values.add(kb.nextInt());
System.out.println("\nYou entered the following values:");
double runningSum = 0;
for(int elem : values) {
runningSum += elem;
System.out.print(elem + " ");
}
System.out.println("\nThe average of the values entered is: "
+ runningSum / values.size());
}
}
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();
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