I am trying to count the number of each character from a to z in a random array of chars of size 100.
import java.util.Random;
public class RandomChars {
public static void main(String[] args) {
Random r = new Random();
String chars= "abcdefghijklmnopqrtuvwxyz";
String[] countc = new String[26];
char[] charArray = new char[100];
for(int i = 1;i<=100;i++)
{
charArray[i-1]=chars.charAt(r.nextInt(chars.length()));
System.out.print(chars.charAt(r.nextInt(chars.length())));
if(i%20==0)
{
System.out.println("");
}
}
//System.out.println(charArray.length);
int m = 0;
int p=0;
for(int n = 0;n<100;n++)
{
char xx = chars.charAt(n);
m = 0;
p=0;
do
{
if(charArray[m]==xx)
{
p=p+1;
}
m=m+1;
}while(m<=charArray.length);
countc[n]=""+p+""+xx;
}
System.out.println("The count of each character is "+ countc);
}
}
> for(int n = 0;n<100;n++)
should be
for (int n =0; n<99; n++)
charArray = 0 to 99 (i-1), but subroutine below you are going 0 to 100 (int n)
do
{
/* ... */
}while(m<=charArray.length);
On the last iteration, m will be equal to charArray.length, so when you call charArray[m], it'll be out of bounds. Change it to while(m < charArray.length); instead.
Change this:
m<=charArray.length
To this:
m<charArray.length
char xx = chars.charAt(n); is getting called all the way up to 99 when chars.charAt() can take a max argument of 25. You need to fix your loop logic so that you check all 100 elements for each of the 26 possible characters, not the other way around.
EDIT: Same thing is happening on your do..while loop.
Firstly, your String chars is omitting the 's' so I've added it in and updated the code to work slightly differently.
After creating the charArray it iterates over each character 26 times (once for each letter). There's probably a much better way to do this but I'm not so hot on Java.
import java.util.Random;
import java.util.Arrays;
public class RandomChars {
public static void main(String[] args) {
Random r = new Random();
String chars= "abcdefghijklmnopqrstuvwxyz";//added the 's'?
String[] countc = new String[26];
char[] charArray = new char[100];
for(int i=0; i<100; i++){
charArray[i]=chars.charAt(r.nextInt(chars.length()));
System.out.print(charArray[i]);
if((i+1)%20==0){
System.out.println("");
}
}
for(int n=0; n<26; n++){//for each of the 26 chars
char xx = (char)chars.charAt(n);
int p=0;
for(int a=0; a<100; a++){//loop through the charArray and count the matches
if(charArray[a]==xx){
p++;
}
}
countc[n]=""+xx+":"+p;
}
System.out.println("The count of each character is "+Arrays.toString(countc));
}
}
http://runnable.com/VCRLPa-2kdoqq2dW/stackoverflow-com-questions-26042877-for-java
Related
public class ForEach {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
void setMarks()
{
for(int j : arr)
{
arr[j] = sc.nextInt();
}
}
void getMarks()
{
for(int k : arr)
{
System.out.println(arr[k]);
}
}
public static void main(String[] args)
{
System.out.println("Enter the marks of 5 subjects : ");
ForEach fe = new ForEach();
fe.setMarks();
System.out.println(fe.arr.length);
fe.getMarks();
}
}
I am just trying to input marks of 5 subjects and display it on the screen. I got this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at ForEach.getMarks(ForEach.java:17)
at ForEach.main(ForEach.java:27)
Your getMarks function is reading an integer out of the array and then trying to go to the position in the array indicated by that integer. If your array has one element and is { 100 }, the code inside your loop will try to print the 100th (really 101st because the index starts at 0) element in your array.
The following code should fix the issue:
void getMarks()
{
for(int k : arr) {
System.out.println(k);
}
}
Also, your setMarks method would set data to only the 0th index. Because "j" points to the value and not to the index.
you might have to refactor you setMarks method like the below -
int pos = 0;
for(int j:arr){
arr[pos] = sc.nextInt();
pos++;
}
or better use the normal for loop.
You use for loop incorrectly. It has two ways to use.
First way
int[] arr = new arr[10];
for(int i = 0; i < arr.length; i++)
arr[i] = 1;
This will set 1 to all elements.
Just why 99% of all usage of for loop just iterates over an array, there is the second way.
int[] arr = { 1,2,3 };
for(int a : arr)
System.out.print(a); // print 123
// i.e. the same
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i]);
Note, that this way you can use only to read element from array from first to last elements.
So, you should change your code to:
public class ForEach {
Scanner sc = new Scanner(System.in);
int[] arr = new int[5];
void setMarks() {
for(int i = 0; i < arr.length; i++)
arr[i] = sc.nextInt();
}
void getMarks() {
for(int a : arr)
System.out.println(a);
}
public static void main(String[] args)
{
System.out.println("Enter the marks of 5 subjects : ");
ForEach fe = new ForEach();
fe.setMarks();
System.out.println(fe.arr.length);
fe.getMarks();
}
}
I am new to java programming and i am trying to sort arrays using Arrays.sort() function. After using Arrays.sort(array),I am printing the final sorted array.
For example:
Input : 1 3 2 4
Output comes as : 0 0 0 0.
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,temp,count;
int[] array = new int[MAX_SIZE];
n = input.nextInt();
for(int i = 0 ; i < n ; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for(int i = 0 ; i < n ; ++i) {
System.out.print(array[i]+" ");
}
}
}
You have initialized you array to hold 20 integers but you input only 5. Hence the first 15 elements will be 0 followed by the numbers you have inputted once the array is sorted.
To fix the issue you can initialize the array with n instead of MAX_SIZE as shown below:-
n = input.nextInt();
int[] array = new int[n];
Set the size of the array to match what your input should be, not to the maximum allowed size:
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, temp, count;
n = input.nextInt();
if (n > MAX_SIZE) {
//handle error somehow
}
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; ++i) {
System.out.print(array[i] + " ");
}
}
}
When you initialize an array in Java it gets default value of 0 for primitive int:
int[] array = new int[MAX_SIZE];
The fact that you are not seeing your desired input of 1,2,3,4 is a separate problem with your Scanner code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}
}
All numbers reverse well but I have problem with reversing numbers that end with zero e.g numbers like 10000 instead of reversing result being 00001 it gives the result as 1 which is not what the question wants is there a way to use integers or string will be the best and easier approach? Thank you
Try the reversing of string concept
String s ="10000";
String n= "";
for(int i=0; i<s.length(); i++){
n = s.charAt(i) + n;
}
System.out.println(n);
You can create a variable length, and use System.out.printf to format output.
With %0 + length + d, it will add 0 on the left to make the output have this length.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
int length = String.valueOf(number).length();
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.printf("%0" + length + "d", reverse);
}
}
}
You could also solve it with a StringBuilder. It already has a method called reverse:
public String reverseInput(int number) {
String s = Integer.toString(number);
return new StringBuilder(s).reverse().toString();
}
You can't have a Integer beginning with 0 except 0 itself. So you will have to work with Strings or other datastructures.
Ok so I'm trying to generate a random character generator that goes beyond simple numbers and letters. I want to simultaneously create a replica of that same generator for the purpose of comparing them and having it print out how many attempts it took for "Cracker" to match the value of "Generator" because I'm interested in the concept after reading a bit of cryptography. When parsing the characters to a string, I get an OutOfBoundsException, but why? I can't seem to find much on the limitations of string. I would think it would have to been an issue besides the string not being able to take the characters but I can't figure it out.
import java.util.Random;
public class Class {
public static void Generator(){
Random r = new Random();
String[] cArray = new String[10];
for(int i = 0; i <= cArray.length; i++){
char c = (char)(r.nextInt(200) + 'a');
String y = Character.toString(c);
cArray[i] = y;
System.out.print(cArray[i]);
}
}
public static void Cracker(){
Random s = new Random();
String[] bArray = new String[10];
for(int x = 0; x <= bArray.length; x++){
char b = (char)(s.nextInt(100) + 'a');
String z = Character.toString(b);
bArray[x] = z;
System.out.print(bArray[x]);
}
}
public static void main(String[] args) {
Generator();
}
}
Any help would be appreciated.
for (int i = 0; i <= cArray.length; i++)
^^^^
Change to
for (int i = 0; i < cArray.length; i++)
^^^^
In both your for loops.
An array of length n has elements from 0 to n-1 - i.e. array arr of length 3 has elements arr[0], arr[1] & arr[2].
I have to make a program that takes duplicate characters from an input array and prints out a new array with all unique characters.
It all works. Except when characters are taken out, it leaves an empty box at the end of that new array.
public class Deleter {
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
char[] initialInputArray = new char[15];
System.out.println("How many characters do you wish to enter?");
int size = keyboard.nextInt();
while ( size > initialInputArray.length ) {
System.out.println("Error. Enter smaller number.");
size = keyboard.nextInt();
}
if( initialInputArray.length <= 15) {
for ( int counter = 0; counter < size; counter++ ){
initialInputArray[counter] = keyboard.next().charAt(0);
}
{
}
}
deleteRepeats(initialInputArray, size);
//Comeback to print out array
{
for ( int helloWorld = 0 ; helloWorld < size ; helloWorld ++)
System.out.print( initialInputArray[helloWorld] );
}
}
//"deleteReapets" method begins, looking for repeated user inputs
public static char[] deleteRepeats (char[] methodArray, int sizeTwo) {
if (sizeTwo == 0)
return methodArray;
if (sizeTwo == 1)
return methodArray;
int uniqueCharacter = 1;
//Start at the second entered character.
for (int x = 1; x < sizeTwo; ++x) {
int y;
for (y = 0; y < uniqueCharacter; ++y) {
if (methodArray[x] == methodArray[y]) break; // break if we find duplicate.
}
if (y == uniqueCharacter) {
methodArray[uniqueCharacter] = methodArray[x]; // add
++uniqueCharacter; // increment uniqueCharacter...[0,uniqueCharacter) is still "unique char list"
}
}
while ( uniqueCharacter < sizeTwo ) {
methodArray[uniqueCharacter] = 0;
uniqueCharacter++;
}
return methodArray;
}
}
That empty box is the null characters that you added at the end of the array. You are printing them because you are not adjusting size according to the number of unique characters (which can be less than the input size). Since you aren't creating a new array, you don't need to return a char [] from deleteRepeats. Instead, you can return the number of unique characters. That way, the calling program knows how many to print.
If your assignment requires that deleteRepeats return a char[], then you should allocate a new array that has a length exactly equal to uniqueCharacter, copy the unique characters to it, and return that. The calling program can just print that new (and shorter) array, rather than printing the first size elements of the input.
Probably the easiest way would be to make a new array to the size of your array of chars and then copy all of the chars into that. The problem with arrays is that once they have been initialized they can't be re sized. If your are familiar with arrayLists I would recommend using them. But if not try something like this...
int count = 0;
for(int i = 0; i < initialInputArray.size; i++){
count++;
}
char[] newArray = new char[count];
for(int i = 0; i < count; i++){
newArray[i] = initialInputArray[i];
}
I would suggest using a HashSet to remove duplicates and wrapping your char to Character. Something like this:
public static Character[] deleteRepeats (char[] methodArray){
HashSet<Character> set = new HashSet<Character>();
for(int index = 0; index < methodArray.length; index++){
set.add(methodArray[index]);
}
return set.toArray(new Character[set.size()]);
}
So in your main method, what you would do is something like this:
Character[] charArray = deleteRepeats(methodArray);
for(int index = 0; index < charArray.length; index++){
System.out.println(charArray[index]);
}