Incorrect logics - java

So the point of this method is to get an array of temperatures above 100. What is wrong with this? When I return this in my toString it says blazing[] doesnt exist.
public int[] above100Degrees()
{
int[] blazing = new int[temps.length];
for( int i = 0; i < temps.length; i++ )
{
if( temps[i] > 100 )
{
blazing[i] = temps[i];
}
}
return blazing;
}
toString method:
public String toString()
{
String returnString = "The temperature forecast of week " + WEEK + " is logged in as: ";
for( int i = 0; i < temps.length; i++ )
{
returnString += "\t" + temps[i] + "\t";
}
returnString += "\n" + "The number of temperatures below freezing is " + getUnderFreeze() + "." + "\n" +
"The largest difference this week was a net change of " + NetChange() + ".";
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
}
return returnString;
}
Output
Forecast.java:122: error: cannot find symbol
for( int i = 0; i < blazing.length; i++ )
^
symbol: variable blazing
location: class Forecast
Forecast.java:124: error: cannot find symbol
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
^
symbol: variable blazing
location: class Forecast
2 errors

The array is returned by the above100Degrees method. It does not establish the variable name blazing in the scope in which it's called. In fact, you can assign the returned array to a variable named differently.
Try
int[] reallyHot = above100Degrees();
// Then check reallyHot...
for( int i = 0; i < reallyHot.length; i++ )
{
returnString += "The temperature above 100 degrees is " + reallyHot[i] + "." + "\n";
}
Make sure to access the specific element with array access syntax.

Change :
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + above100Degrees() + "." + "\n" + "\t" + blazing[i] + "\t";
}
to :
int[] blazing = above100Degrees();
for( int i = 0; i < blazing.length; i++ )
{
returnString += "The temperature above 100 degrees is " + blazing[i] + "."; // personalise format
}

Your above100Degrees() function returns the array blazing but you don't invoke that function in your toString() method. As far as toString() is concerned blazing doesn't exist.
Call above100Degrees() from within toString() and save the resulting array to a variable. Then you'll be able to iterate over the (newVariable).length instead of blazing.length.

Related

Displaying number of times a character is in a string

I need to print the amount of times an input character appears in the string. It runs and works for all tests, however when a character appears only 1 time it prints "1 times" instead of "1 time" like expected, and i am unsure of how to add this into my code. It has to be when count is equal to 1 the outprint changes from times to time. I am lost.
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
Expected to
You should add a condition for the same instead of printing the static string "times" as below:
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
String str = (count==1)?"time":"times";
System.out.println("The letter '" + letter + "' appears " + count + str + " in the string " + "\"" + input + ".\"");
Maybe try something like this
String plural = (count == 1) ? "" : "s";
System.out.println("The letter '" + letter + "' appears " + count + " time" + plural + "in the string " + "\"" + input + ".\"");
I would use an if statement to determine how many times this specific letter appears in your string. Also, since first character is charAt(0), the last character should be charAt(s.length()-1);.
for( i = 0; i < (input.length()-1); i ++){
if (input.charAt(i) == letter)
count = count + 1;
} //end of your for loop
if (count == 1){
System.out.println("The letter '" + letter +
"' appears " + count + " time in the string " + "\"" + input + ".\"");
}
else{
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
}

how to call httpconeection setRequestProperty android in loop to setHeader?

HTTPConnection conn method
setRequestProperty
conn.setRequestProperty("","");
I have different header for different URL. So, it's not fix in my project.
I need to use a array to fill the setRequestproperty data.
Individual call for setRequestProperty it's working 1stPart .
I tried to call same into Array it's not work "part 2".
1) conn.setRequestProperty("Authorization","12345678");
conn.setRequestProperty("ReToken", "erjeorjeorjeoureorjr");
2)
String[] array1 = new String[]{"Authorization","12345678","RefreshToken","erjeorjeorjeoureorjr"};`
if (array1 != null) {
int size = array1.length;
for (int i = 0; i < size; i = i + 2) {
conn.setRequestProperty('"' + array1[i] + '"',
'"' + array1[i + 1] + '"');
Log.d(TAG,"Value Print:: " + array1[i] + " ," +
array1[i+1] );
}
}
You are trying to convert something that is already a string into a string. Just remove the double quotes around the array.
Try this:
for (int i = 0; i < size; i = i + 2) {
conn.setRequestProperty(array1[i] ,array1[i + 1]);
Log.d(TAG,"Value Print:: " + array1[i] + " ," + array1[i+1] );
}

java StringIndexOutOfBoundsException: String index out of range: 0

Its a very simple function. I don't know why it is giving an StringIndexOutOfBoundsException for the function source.charAt(i). I have checked the values of 'i' are not exceeding the length of the string which will be always 9.
public static String getClockResetString(String source, String target, Hashtable order)
{
String temp = "",name;
for(int i = 0; i < source.length(); i++){
name = (String)order.get(""+i);
if(source.charAt(i) != target.charAt(i))
{
if((int)source.charAt(i) < (int)target.charAt(i)){
temp = "h" + name + "=" + "dp" + name + "0" + " do " + "{h" + name + "'=0, k'=k+1} ";
}
else{
temp = "h" + name + "=" + "dn" + name + "1" + " do " + "{h" + name + "'=0, k'=k+1} ";
}
}
}
return temp;
}
I bet that you are exceeding the bounds on target, not source
if(source.charAt(i) != target.charAt(i))
You need to check that
i < target.length()

Java String letter counter not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!
import java.util.Scanner;
public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
int strslength = strs.length();
int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;
for(int i = 0; i <= strslength; i++)
{
if (strs.substring(i, i) == "a")
{
numa = numa + 1;
}
if (strs.substring(i, i) == "b")
{
numb = numb + 1;
}
if (strs.substring(i, i) == "c")
{
numc = numc + 1;
}
if (strs.substring(i, i) == "d")
{
numd = numd + 1;
}
if (strs.substring(i, i) == "e")
{
nume = nume + 1;
}
if (strs.substring(i, i) == "f")
{
numf = numf + 1;
}
if (strs.substring(i, i) == "g")
{
numg = numg + 1;
}
if (strs.substring(i, i) == "h")
{
numh = numh + 1;
}
if (strs.substring(i, i) == "i")
{
numi = numi + 1;
}
if (strs.substring(i, i) == "j")
{
numj = numj + 1;
}
if (strs.substring(i, i) == "k")
{
numk = numk + 1;
}
if (strs.substring(i, i) == "l")
{
numl = numl + 1;
}
if (strs.substring(i, i) == "m")
{
numm = numm + 1;
}
if (strs.substring(i, i) == "n")
{
numn = numn + 1;
}
if (strs.substring(i, i) == "o")
{
numo = numo + 1;
}
if (strs.substring(i, i) == "p")
{
nump = nump + 1;
}
if (strs.substring(i, i) == "q")
{
numq = numq + 1;
}
if (strs.substring(i, i) == "r")
{
numr = numr + 1;
}
if (strs.substring(i, i) == "s")
{
nums = nums + 1;
}
if (strs.substring(i, i) == "t")
{
numt = numt + 1;
}
if (strs.substring(i, i) == "u")
{
numu = numu + 1;
}
if (strs.substring(i, i) == "v")
{
numv = numv + 1;
}
if (strs.substring(i, i) == "w")
{
numw = numw + 1;
}
if (strs.substring(i, i) == "x")
{
numx = numx + 1;
}
if (strs.substring(i, i) == "y")
{
numy = numy + 1;
}
if (strs.substring(i, i) == "z")
{
numz = numz + 1;
}
}
System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
}
public static void main(String[] args)
{
stringinputmethod();
}
}
Correct usage of the substring method:
strs.substring(i, i)
needs to be
strs.substring(i, i + 1)
because the char at lastIndex is not included in the output.
Correct comparison of Strings in Java
Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator.
This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()
Proper storing of data
Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.
Instead of
int numa = 0;
....
int numz = 0;
you should use arrays, or even better Map<Character,Integer>.
strs.substring(i, i) == "a" have two problems:
substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").
You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like
for (char ch : strs.toLowerCase().toCharArray()){
//do something based on value of `ch`
}
Try this:
It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.
What does it do?
If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time.
By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.
package lettercounter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* #author edm
*/
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
//this map will be populated with the occurrence of the letters in the string.
HashMap<String, Integer> countenLetters = new HashMap<>();
//the next line generates a key-value-store whose key is the letter in the string
//and the value is the accumulated occurrence of said letter.
Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
Integer count = 0;
try {
count = countenLetters.get(letter).intValue();
} catch (Exception e) {
//tried to access a non existing value in the map
//this happens if there is a letter which was not set in the map until now.
//i.e. the first time the letter is encountered.
//this is no error. could have done it with an if also.
}
countenLetters.put(letter, ++count);
});
//do with this stuff what you want;
countenLetters.forEach((k,v) -> {
System.out.println("Letter "+k+" occurs "+v+" times in the string.");
});
}
}

NullPointer Exception Jcreator, Java

I am having an incredibly difficult time trying to figure out why I am getting this error.
When I use a driver file to test the program it fails horribly.
Here's my code:
import java.util.Scanner;
import java.lang.Math.*;
public class Histogram
{
private int[] arrayData;
private int[] arrayRange;
private final int LOW = 1;
private final int HIGH = 100;
public Histogram()
{
int[] arrayData = new int[11];
}
public void getInput()
{
int[] arrayRange = new int[11];
for(int count = 1; count < arrayRange.length; count++)
{
arrayRange[count] = count * 10;
}
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers from 1 to 100, Type -999 to quit.");
int nextNumb = input.nextInt();
while(nextNumb != -999)
{
if(nextNumb >= LOW && nextNumb <= HIGH)
{
for(int i = 0; i <= arrayRange.length; i++)
{
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
}
nextNumb = input.nextInt();
}
else arrayData[10]++;
nextNumb = input.nextInt();
}
}
public String starPrint(double count)
{
String star = "";
count = (Math.round(count) / 5);
for(int i = 1; i <= count; i++)
{
star = star + "*";
}
return star;
}
public String toString()
{
String results = " Range | Histogram" + "\n";
results = results + "1 - 10 | " + starPrint(arrayData[0]) + "\n";
results = results + "11 - 20 | " + starPrint(arrayData[1]) + "\n";
results = results + "21 - 30 | " + starPrint(arrayData[2]) + "\n";
results = results + "31 - 40 | " + starPrint(arrayData[3]) + "\n";
results = results + "41 - 50 | " + starPrint(arrayData[4]) + "\n";
results = results + "51 - 60 | " + starPrint(arrayData[5]) + "\n";
results = results + "61 - 70 | " + starPrint(arrayData[6]) + "\n";
results = results + "71 - 80 | " + starPrint(arrayData[7]) + "\n";
results = results + "81 - 90 | " + starPrint(arrayData[8]) + "\n";
results = results + "91 - 100 | " + starPrint(arrayData[9]) + "\n";
results = results + "Outliers: " + starPrint(arrayData[10]) + "\n";
return results;
}
}
I believe that the problem is in my getInput method
right here to be precise:
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
I have no idea what's wrong with it though I am a beginner programmer and couldn't find a solution to this particular problem.
Thanks for any help you're able to give!
public Histogram()
{
int[] arrayData = new int[11];
}
You're shadowing your arrayData field in the constructor. This is creating a local variable with the same name as your class's arrayData field, initializing it, then immediately discarding it. When you try to use the field later in your code, it's null. Get rid of the int[] part.
Note that your next exception will be an ArrayIndexOutOfBoundsException ... you should look at your loop ;)
this: for(int i = 0; i <= arrayRange.length; i++)
wont work since you are trying to access arrayRange[i] and arrayRange[i+1]
which dont exists for i = arrayRange.length-1 and further
so change it to:
for(int i = 0; i < arrayRange.length-1; i++)

Categories