I know there is an easier way to solve this problem statement now. But this is something i tried and wasn't able to debug.
This is my code.
String str="java is a programming language";
int flag=0,k=0;
char unique[]=new char[256];
for(int i=0;i<str.length();i++){
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
flag++;
}
System.out.println(flag); //printing flag values
if(flag==0){
unique[k]=str.charAt(i);
System.out.println(unique[k]); //printing array values
k++;
}
}
And this is my output.
Enter the sentence:
java is a programming language
0
j
5
5
9
12
13
13
15
18
19
19
20
20
23
23
25
26
26
26
27
29
29
29
30
30
31
31
31
31
31
Unique characters:
j
I want to understand from where these number values are getting printed. I was certain printing flag values and array values will give me single digit numbers. What are all these double digit numbers?
you just need to reset the counter(flag) before adding to it in the next iteration.
flag=0;
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
flag++;
}
Your code has the following problems:
Not resetting the value of flag.
Printing flag for each value of i whereas you wanted to print it only on finding a unique character.
You are starting the loop with j from i + 1 and this way, you will not be able to compare the characters before the index, i + 1.
Some additional things you may also like to do are:
Filtering only non-blank characters.
Printing the array only up to the value of k.
Not fixing the size of unique[] to 256. If all characters in str are unique, the required size of unique[] will be equal to the length of str. Thus, the maximum required size of unique[] is equal to str.length(). However, it is always better to use a List if the size needs to be dynamic.
Store and print unique characters as follows:
public class Main {
public static void main(String[] args) {
String str = "java is a programming language";
int flag, k = 0;
char unique[] = new char[str.length()];// This array can have a maximum length equal to the length of str
for (int i = 0; i < str.length(); i++) {
flag = 0;
for (int j = 0; j < str.length(); j++) {
if (i != j && str.charAt(i) == str.charAt(j)) {
flag++;
}
}
if (flag == 0 && !String.valueOf(str.charAt(i)).isBlank()) {
unique[k] = str.charAt(i);
k++;
}
}
System.out.print("Unique characters: ");
for (int i = 0; i <= k; i++) {
System.out.print(unique[i] + (i < k - 1 ? "," : "\n"));
}
}
}
Output:
Unique characters: j,v,s,p,o,l,u,e
String str="java is a programming language";
int flag=0,k=0;
char unique[]=new char[256];
for(int i=0;i<str.length();i++){
flag = 0;
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
flag++;
}
System.out.println(flag); //printing flag values
if(flag==0){
unique[k]=str.charAt(i);
System.out.println(unique[k]); //printing array values
k++;
}
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am still new to Java, this question like: An ISBN-10 (International Standard Book Number)
consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum,
which is calculated from the other nine digits using the following formula:
(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11
If the checksum is 10, the last digit is denoted as X according to the ISBN-10
convention. Write a program that prompts the user to enter the first 9 digits and
displays the 10-digit ISBN (including leading zeros). Your program should read
the input as an integer.
See my code below:
It is working but the result is not correct!
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 0 ; i < arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 0 ; j < arr.length; j++)
{
System.out.print(arr[j]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
I just want to use loop, make my method works. , i know how to use method without loop.
well. for JAVA
an array index start from 0. and Max index is length - 1.
if the index is not within this range. an arrayoutofbounds exception will be thrown
The problem is not that you are doing int i = 1 instead of int i = 0. The problem is that you changed i < arr.length; to i <= arr.length;. Since arr.length is 9, your code is trying to refer to arr[9] but arr only has elements arr[0] through arr[8].
First, review how we use arrays...
int[] I = new int[3];
The above creates an array with 3 spots in it. After instantiating the array, each element is based off of a 0-index. You only have I[0], I[1], and I[2] available (note this is three numbers) and trying to access I[3] will throw the error that you encountered in your program above: ArrayIndexOutOfBoundsException.
That being said, your loop is trying to access arr[9]. The highest index you have in the array is arr[8], because despite the array having 9 elements in it, it's 0-indexed.
Assuming you MUST have i starting from 1 for a homework assignment or something, change your code to:
public static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.print("Enter first 9 digit numbers: ");
int[] arr = new int[9];
int checkSum = 0;
for (int i = 1 ; i <= arr.length; i++)
{
arr[i-1] = input.nextInt();
checkSum = (arr[i-1] * i) % 11;
}
System.out.print("The ISBN-10 Number is " );
for(int j = 1 ; j <= arr.length; j++)
{
System.out.print(arr[j-1]);
}
if(checkSum == 10)
{
System.out.println("x");
}
else
{
System.out.println(checkSum);
}
int[] arr = new int[9];
This means the array has 9 slots. And the numbering of those slots starts from 0. Thus,
arr[0] is the first slot
arr[1] is the second slot
The last slot would be arr[8]. But in the following code you are iterating till i is equal to 9 which does not exist.
for (int i = 1 ; i <= arr.length; i++)
{
arr[i] = input.nextInt();
checkSum = (arr[i] * (i+1)) % 11;
}
This results in the ArrayIndexOutOfBoundsException. Change for (int i = 1 ; i <= arr.length; i++) to for (int i = 0 ; i < arr.length; i++)
I was given a lab assignment where we were asked to fill an array of size 50. The first 25 elements had random distinct elements, and the remaining have to be each 26 . All we have to do is print the repeating element,which obviously is 26, using the Las Vegas Algorithm .
I wrote the program and since it's my first time at Java , I am stuck with an exception of Array indexes out of bounds.
I am also sure that there is nothing wrong with the algorithm, and please note that I first created a list and then converted it to array of Integer type.
Hoping for a helping hand.
The code is as follows :-
public class NewClass {
static Random randomGenerator = new Random();
public static void lasveg(Integer a[],int n)
{
int i,j;
boolean chk= true;
while(chk)
{
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
if((i!=j)&&(a[i].equals(a[j])))
System.out.println("The repeated element is : " + i);
}
}
public static void main(String[] args)
{
int i ;
Integer[] arr = new Integer[50] ; //used the Integer wrapper class instead of primitive int
ArrayList list = new ArrayList(50);
for (i=1; i<26; i++)
{
list.add(i) ;
}
Collections.shuffle(list);
for(i=26 ; i<51 ; i++)
{
list.add(26) ;
}
list.toArray(arr) ;
for(i=0 ; i<50 ; i++)
{
System.out.print(arr[i] + " ");
}
lasveg(arr,50);
}
}
The code has several issues:
randomGenerator.nextInt() could return negative numbers and you
can't use negative numbers as index for an array.
if you use % n+1 then you could get an index bigger than 49, which
should be the highest index in an array of length 50.
the third thing is that you have a endless loop, because you never
end the while(true)
If you change all that then your code could look like that:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class NewClass {
static Random randomGenerator = new Random();
public static void lasveg(Integer a[], int n) {
int i, j;
boolean chk = true;
while (chk) {
i = Math.abs(randomGenerator.nextInt()) % n ;
j = Math.abs(randomGenerator.nextInt()) % n ;
if ((i != j) && (a[i].equals(a[j]))){
System.out.println("The repeated element is : " + i);
break;
}
}
}
public static void main(String[] args) {
int i;
Integer[] arr = new Integer[50]; // used the Integer wrapper class
// instead of primitive int
ArrayList list = new ArrayList(50);
for (i = 1; i < 26; i++) {
list.add(i);
}
Collections.shuffle(list);
for (i = 26; i < 51; i++) {
list.add(26);
}
list.toArray(arr);
for (i = 0; i < 50; i++) {
System.out.print(arr[i] + " ");
}
lasveg(arr, 50);
}
}
Output:
24 20 19 14 13 16 10 7 22 18 12 15 2 6 3 25 17 8 1 21 4 5 11 23 9 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 26 The repeated element is : 26
If you call this function with n = 50 and your array a got 50 elements
public static void lasveg(Integer a[],int n)
{
int i,j;
boolean chk= true;
while(chk)
{
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
if((i!=j)&&(a[i].equals(a[j])))
System.out.println("The repeated element is : " + i);
}
}
Whats happen there is if the random number is (50*x)-1 % 50 + 1 you calling a[50] thats throwing an out of range exception.
You aint want to increase the term rand % n then you get a range from 0 to 49.
Your i and j variables are assigned a random number in the segment from 0 to n, including n
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
In Java the index of the last element of array of n elements is n-1, so there is a possibility, that this statement
if((i!=j)&&(a[i].equals(a[j])))
System.out.println("The repeated element is : " + i);
will cause the index out of bound exception.
The problem that you have here it's that you have to notice that arrays starts at position 0.
array[0];
So, when you use your method lasveg you are setting the number 50 and really trying to access to the position 51 where you do a[i] and a[j] here:
if((i!=j)&&(a[i].equals(a[j])))
To fix your problem you will have to do:
lasveg(arr,49);
Another solution it's to avoid the + 1 in your Random. Change this:
i=(randomGenerator.nextInt())%n+1;
j=(randomGenerator.nextInt())%n+1;
to this:
i=(randomGenerator.nextInt())%n;
j=(randomGenerator.nextInt())%n;
I expect it will be helpful for you!
I wanted to write code that reads a word stored as a String variable. The program should loop through each character in the word and update an array that contains the frequency with which each letter occurs.
The letters in the alphabet (A to Z) can be referenced by "freq[1]" to "freq[26]".
However, when I try to run my program, I get an error that says:
java.lang.ArrayIndexOutOfBoundsException: -64
at ReadWords.main(ReadWords.java:17)
Here is the code I used:
public class ReadWords
{
public static void main (String[] args)
{
String line = "This is a line of text. That's not exciting";
line = line.toLowerCase();
int[] freq = new int[27];
for (int i = 0; i < line.length(); i++)
{
int letter = line.charAt(i) - 96;
freq[letter]++;
}
for (int i = 0; i < freq.length - 1; i++)
{
System.out.println(freq[i]); //prints all elements in the array
}
}
}
Because you are reading space characters (ASCII 32) with your letters. Its value is 32, and when you subtract 96, you get -64, obviously not a valid array index.
I don't think you want to count spaces, so skip them; don't process them.
You'll want to skip other punctuation characters as well, with ' being ASCII value 39, and . being ASCII value 46.
Your error
Like rgettman said, you're including the spaces in your analysis of the frequence. Simply add an if-statement.
for (int i = 0; i < line.length(); i++)
{
int letter = line.charAt(i) - 96;
if (letter > 0 && letter < 27) freq[letter]++;
}
if (letter > 0 && letter < 27) makes sure that the char that you're at in your String is in fact a letter from a - z
Helpful points
Also, in your second for-loop, it won't display the frequency of 'z', and it will display the frequency as position 0 in the array, which holds nothing (position 1 is 'a').
You need to change this:
for (int i = 0; i < freq.length - 1; i++)
to this:
for (int i = 1; i < freq.length; i++)
This way it includes element 27, which is freq[26], which is where the 'z' frequency is. It also will ignore element 1, which is freq[0]. Try it. Or you could change the size of your freq array to 26, and subtract 97 from the line.charAt(i) and then change the if-statement I gave you in your first for-loop to
if (letter > -1 && letter < 26). And then use for (int i = 0; i < freq.length; i++).
Display the letter with the frequency
Use this line of code to display the char corresponding to the frequency as well:
System.out.println((char)(i + 96) + ": " + freq[i]);
Or if you did what I said where you changed the size of the freq array and made the frequency of 'a' at position 0, use this line:
System.out.println((char)(i + 97) + ": " + freq[i]);
I guess the easiest way to do this would be to only check for lower case alphabets (97-122 ASCII values).
Below is the modified version of your code.
public static void main(String[] args) {
String line = "This is a line of text. That's not exciting";
line = line.toLowerCase();
int[] freq = new int[27];
for (int i = 0; i < line.length(); i++) {
/*Only use lower case alphabets ranging from 97 to 122.
The below if should omit all other unwanted characters from your string.*/
if (line.charAt(i) > 96
&& line.charAt(i) < 123) {
/* Subtract by 97 to start your array from 0 for a(value 97)*/
int letter = line.charAt(i) - 97;
freq[letter]++;
}
}
for (int i = 0; i < freq.length - 1; i++) {
System.out.println((char)(i+97) + " : " + freq[i]); // prints all elements in the array
}
}
I need some help with this assignment I've been given. Not asking anyone to do my work but I'm really honestly stuck on how to even do this.
I'm supposed to write a program that prompts the user to enter 10 numbers and then have it write all the numbers in reverse order.
Example:
Enter 10 Numbers: 23 89 21 55 67 89 99 13 98 78
Reverse Order: 78 98 13 99 89 67 55 21 89 23
So far all I have is how to get the user inputs. If anyone can push me in the right direction, i'd be very grateful!
import java.util.*;
public class ReverseNumbers
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter 10 numbers:");
for (int i = 0; i< values.length; i++)
{
values[i] = keyboard.nextInt();
}
int[] reverseNums;
reverseNums = new int[10];
for (int i = (values.length -1); i>= 0; i--)
{
reverseNums[ reverseNums.length -1 -i ] = values[ i ];
System.out.println( reverseNums[ i ] );
}
}
}
If you dont want to store the reversed values
for (int i = (values.length -1); i>= 0; i--)
{
System.out.println( values[ i ] );
}
Your code looks good for reading inputs into values. Now you can loop over that array in reverse and print the values:
for (int i = 0; i < values.length; i++)
System.out.println(values[values.length - i - 1]);
Think about it, when i == 0 it will print values[9] since 10 - 0 - 1 = 9. At the end, when i == 9 it will print values[0] since 10 - 9 - 1 = 0.
As you can see, there is no need for the extra reverseNums array.
PS: If you want, you can combine int[] values; and values = new int[10]; into a single line: int[] values = new int[10];
Read in the whole line as a string using Scanner.nextLine(), and then split it into an array using String.split(" ");. After this, you can simply iterate from the end of the array going backwards and print the numbers.
If it's not an assignment then why not try using http://commons.apache.org/proper/commons-lang/ library
ArrayUtils.reverse(int[] array)
I think your code is creating the array correctly. You are just printing out the numbers in the original order because your second for-loop is iterating over them backwards. You can see the correct result by adding the statement below after the last loop:
System.out.println(java.util.Arrays.toString(reverseNums));
You can also perform the complete task with only one iteration:
Scanner keyboard = new Scanner(System.in);
int[] reverseNums= new int[10];
System.out.println("Please enter 10 numbers:");
for (int i = 0; i< values.length; i++) {
reverseNums[values.length -1 - i] = keyboard.nextInt();
}
System.out.println(java.util.Arrays.toString(reverseNums));
To reverse it:
for (int i = 0; i < values.length; i++)
reverseNums[values.length - i - 1] = values[i];
Ok im going to try and explain my problem here and what I need to do is convert a string array into an int array.
Here is part of what I have (well the initial set up)
System.out.println("Please enter a 4 digit number to be converted to decimal ");
basenumber = input.next();
temp = basenumber.split("");
for(int i = 0; i < temp.length; i++)
System.out.println(temp[i]);
//int[] numValue = new int[temp.length];
ArrayList<Integer>numValue = new ArrayList<Integer>();
for(int i = 0; i < temp.length; i++)
if (temp[i].equals('0'))
numValue.add(0);
else if (temp[i].equals('1'))
numValue.add(1);
........
else if (temp[i].equals('a') || temp[i].equals('A'))
numValue.add(10);
.........
for(int i = 0; i < numValue.size(); i++)
System.out.print(numValue.get(i));
Basically what I am trying to do it set 0-9 as the actual numbers and then proceed to have a-z as 10-35 from the input string such as Z3A7 ideally would print as 35 3 10 7
Try this in your loop:
Integer.parseInt(letter, 36);
This will interpret letter as a base36 number (0-9 + 26 letters).
Integer.parseInt("2", 36); // 2
Integer.parseInt("B", 36); // 11
Integer.parseInt("z", 36); // 35
You can use this single line in the loop (assuming user doesn't enter empty string):
int x = Character.isDigit(temp[i].charAt(0)) ?
Integer.parseInt(temp[i]) : ((int) temp[i].toLowerCase().charAt(0)-87) ;
numValue.add( x );
Explanation of the code above:
temp[i].toLowerCase() => z and Z will convert to the same value.
(int) temp[i].toLowerCase().charAt(0) => ASCII code of character.
-87 => Substracting 87 for your specification.
Considering that you want to denote Z as 35, I have written the following function
UPDATE :
The ASCII value for Z is 90, so if you want to denote Z as 35 then you should subtract every character from 55 as (90-35=55):
public static int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
int intarray[] = new int[sarray.length];
for (int i = 0; i < sarray.length; i++) {
if (sarray[i].matches("[a-zA-Z]")) {
intarray[i] = (int) sarray[i].toUpperCase().charAt(0) - 55;
} else {
intarray[i] = Integer.parseInt(sarray[i]);
}
}
return intarray;
}
return null;
}