This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I want to pick a particular “short” word in an array of words, that is, words with at most three characters.
For this example, if you are passed an array containing the strings
"Mary", "had", "a", "little", "lamb"
and you are asked to return the second short word, you would return "a".
import java.util.*;
public class Numbers
{
String[] words = {"Mary", "had" , "a" , "little" , "lamb"};
int n = 2;
public String Numbers;
String[] word;
{
int counter = 1;
int length = 0;
int count = 0;
for (int i = 0; i < words.length; i++)
{
length = words[i].length();
if (length <= 3)
{
count++;
**word[count] = words[i];**
}
}
String answer = word[n];
System.out.println(answer);
}
}
When I run the code, it gives me a null exception error, and I'm not sure how to fix it. The debugger told me it had to do something with the
word[count] = words[i];
What is wrong with my code?
The array needs to init.
String[] word = new String[10];
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
Below mentioned code is for reversing k elements in a string of n size. Line 3 is returning garbage value. Can anyone please help me out on this.
class Solution{
public String reverseStr(String s, int k){
char[] ch = s.toCharArray();
Stack<Character> st = new Stack();
int i;
for(i = 0; i < k; i++){
st.push(ch[i]);
}
i = 0;
while(!st.isEmpty()){
ch[i] = st.pop();
}
return ch.toString();
}
}
Increment i
There is a mistake in this part of your code:
i = 0;
while(!st.isEmpty()){
ch[i] = st.pop();
}
Note that i remains 0 the whole time, so you are assigning to ch[0] in each iteration of the loop. You probably meant to increment i in the loop:
i = 0;
while(!st.isEmpty()){
ch[i++] = st.pop();
}
Generate String from char array
Note that the last line of your code:
return ch.toString();
will not return what you expect. If you want to convert the char array to a String containing the characters, do this instead:
return new String(ch);
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
question i am trying to solve.
You are given n triangles.
You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle.
sample input:
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3
here is my code:
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] = arr[i][j]+arr[i][j+1]; //possible error
}
}
for (int i=0;i<testCases;i++){
for (int j=i+1;j<testCases;j++) { //possible error
if (result[i]!=result[j]){
count++;
}
}
}
System.out.println(count);
}
}
error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at P1.TestClass.main(Solution.java:21)
how to correct the loops so as to not get the errors(note there maybe other errors than the one's i have highlighted) also some better ways of solving this problem are appreciated.
Your program has an ArrayIndexOutOfBoundException in the line result[i] = arr[i][j]+arr[i][j+1];. And I am not sure your second set of nested loops achieve what you want (Summing the triangles). Here is something that can work.
class TestClass {
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
int arr[][]=new int[testCases][3];
int count=0;
for (int i = 0; i < testCases; i++) {
for (int j=0;j<3;j++){
arr[i][j]=scanner.nextInt();
}
}
//This section sums each set of three
int result[] =new int[testCases];
for (int i = 0; i < testCases; i++) {
for (int j = 0; j < 3; j++) {
result[i] += arr[i][j];
}
}
//This section counts values that are not duplicated
for (int i=0;i<testCases;i++){
boolean hasDuplicate = false;
for (int j=0;j<testCases;j++) {
if (i == j) continue; //skip comparison of value against itself
if (result[i]==result[j]){
hasDuplicate = true; //duplicate found
}
}
if (!hasDuplicate) count++;
}
System.out.println(count); //display number of unique entries
}
}
I don't want to be doing any homework for you, so I'll give you some pointers. Try not to have a look at a solution I have come up with below before trying it yourself again though.
I'd use an ArrayList to store the test data given to you. They're really useful and Java has great support for them.
result[i] = arr[i][j]+arr[i][j+1]; This breaks because j+1 will always be one over the final index of your array.
You can sort strings alphabetically using Arrays.sort which will make comparing triangles much easier, as possible combinations will all end up the same.
Collections.frequency will tell you how many times an element appears in your ArrayList.
My solution certainly isn't the best, and uses more advanced things as apposed to just arrays and booleans, but it works and produces the right answer at the end. It shows that you can solve problems in many different ways!
public static void main(String[] args) {
ArrayList<String> triangleArray = new ArrayList<String>();
Scanner scanner = new Scanner(System.in);
int uniqueTriangles = 0;
// Ask for input, and store in a string that remove all whitespace
System.out.print("Enter triangle sides in format abc separated by a comma:");
String input = scanner.nextLine().trim().replaceAll("\\s", "");
triangleArray.addAll(Arrays.asList(input.split(",")));
// For each item, check it is three characters, and if so, reorder them in
// ascending order i.e 726 => 267
for (int i = 0; i < triangleArray.size(); i++) {
if (triangleArray.get(i).length() != 3) {
triangleArray.remove(i);
}
// Split the triangle string into a character array and sort 'alphabetically'
char[] charArray = triangleArray.get(i).toCharArray();
Arrays.sort(charArray);
triangleArray.set(i, new String(charArray));
}
// Now go through them all again and see if any are unique
for (String s : triangleArray) {
if (Collections.frequency(triangleArray, s) < 2) {
uniqueTriangles++;
}
}
System.out.println(uniqueTriangles);
}
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 5 years ago.
I am working on a code for homework where we have to use a char array holding a sentence and reverse the order of array so that the words are in opposite order in java for example "I am a house" should put out "house a am I" I am stuck on how to actually step through and order the array so the words go in this order any tips will help.
The code i have reverses the whole array but it does not put reverse it word by word
if(sentence.length%2 == 0)
{
int middleR = sentence.length/2;
int middleL = middleR - 1;
for(int i = middleR; i < sentence.length; i++)
{
char temp = sentence[i];
sentence[i] = sentence[middleL];
sentence[middleL] = temp;
middleL--;
}
}
else
{
int middle = sentence.length/2;
int end = sentence.length -1;
for(int i = 0; i < middle;i++)
{
char temp = sentence[i];
sentence[i] = sentence[end];
sentence[end] = temp;
end --;
}
}
Split the text into an array of Strings (String.split), put the array into a List (Arrays.asList), revers the list (Collections.reverse), get String array from the list (List.toArray)
This question already has answers here:
Split string to equal length substrings in Java
(23 answers)
Closed 5 years ago.
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
Array should look like array = {"abcd","efgh","ijkl"...."yz"} after my work.
Here is what I have tried:
WORK1:
int strIndex = 0;
int arrayIndex=0;
for(strIndex=0; strIndex<str.length();strIndex++) {
array[arrayIndex] += Character.toString(str.charAt(strIndex));
if((strIndex % 4 == 0) && (strIndex != 0 ))
arrayIndex++;
}
========================================================================
WORK2:
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0; // 0->4->8->12..
int end = 4; // 4->8->12->16...
System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
array[i] = str.substring(start,end);
start+=4;
end+=4;
}
===========================================
WORK1: it gives me the output of abcde fghi jklm nopr qstu vwxy z, which is wrong
WORK2: Because substring() jumps by 4, it will be the cause of Exception when it access the index of 28. Last part should be: (str.substring(24,26));, I can't think of efficient way to handle this.
Any advice will be appreciated.
You Need to restrict the Substring end to the strings Maximum lenght:
// pseudocode - you did not supply a tag for the language you are using
str.Substring(start,Math.Min(str.Count,end)) // Math.Min == C#
WORK1 should work with a minor change.
Currently you're putting "abcde" into the first array element simply because you're adding the 0th, 1st, 2nd, 3rd and 4th elements. You want to seperate before the 4th element not after. Give this a try:
int strIndex = 0;
int arrayIndex=0;
for(strIndex=0; strIndex<str.length();strIndex++) {
if((strIndex % 4 == 0) && (strIndex != 0 ))
arrayIndex++;
array[arrayIndex] += Character.toString(str.charAt(strIndex));
}
Hopefully this helps. Let me know how you get on!
Check the below code sniplet, it works fine as you said.
Let me know if any issues. (Added a syso just to validate the answer :) )
String str = "abcdefghijklmnoprqstuvwxyz";
String[] array = new String[str.length()/4 +1];
int start = 0; // 0->4->8->12..
int end = 4; // 4->8->12->16...
int length = str.length();
System.out.println("arraylength:"+array.length);
for(int i=0;i<array.length;i++) {
array[i] = str.substring(start,end);
start+=4;
end+=4;
System.out.println(array[i]);
if(end>length)
end=length;
}
This question already has answers here:
A quick and easy way to join array elements with a separator (the opposite of split) in Java [duplicate]
(15 answers)
Closed 6 years ago.
I need to print this array without having he last array item print with a comma. I have tried setting i to be less than 3 but it will not work. :/ I cannot get this last array entry to print all by itself. This is homework so please do not feel the need to give me the answer just a nudge in the right direction would help!
import java.util.Scanner;
public class PrintWithComma {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] hourlyTemp = new int[NUM_VALS];
int i = 0;
hourlyTemp[0] = 90;
hourlyTemp[1] = 92;
hourlyTemp[2] = 94;
hourlyTemp[3] = 95;
for(i = 0; i < NUM_VALS; i++){
if(hourlyTemp[i] < NUM_VALS);
System.out.print(hourlyTemp[i]);
}
System.out.println("");
return;
}
}
Since you just want a nudge in the correct direction,
if(hourlyTemp[i] < NUM_VALS);
Remove the semicolon at the end of that if (it terminates the if body). Also, I suggest you always use braces
if(hourlyTemp[i] < NUM_VALS) {
// ...
}
I also think you wanted i + 1 < NUM_VALS and System.out.print(", "); Of course, you might also use
System.out.println(Arrays.toString(hourlyTemp));
Edit
Based on your comment below you seem to want something like
for (i = 0; i < NUM_VALS; i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(hourlyTemp[i]);
}
System.out.println("");