Alright so I've created an array of type int with size 10.
I've initialized it to random values between 1-100.
Now my task is to write a method named output which will take an int array as a parameter and displays all elements of the array in a column like this:
Output
arr[0] : 17
arr[1] : 42
etc etc, but when I do it in eclipse it says
i cannot be resolved to a variable,
so I was thinking of re-initializing it in my method, but wouldn't that give me a whole set of different numbers?
private int [] nums;
public UsingArrays(){
nums = new int [10];
for (int i = 0; i <nums.length; i++){
nums[i] = (int)(Math.random()*100)+1;
}
}
public String Output(){
String string;
string = "Arr[" + i + "]:" + nums[i];
return string;
}
}
i cannot be resolved to a variable
You forgot to surround the whole thing with a for loop that will be declaring & using that i variable :
public void Output(int[] array){
String string = "";
for(int i = 0; i < array.length; i++) {
string += "Arr[" + i + "]:" + array[i] + "\n"; // not recommended
}
System.out.println(string);
}
And in such cases, it would be better if you use a StringBuilder, so as to avoid creating new String instances at each iteration:
public void Output(int[] array){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < array.length; i++) {
sb.append("Arr[" + i + "]:" + array[i] + "\n"); // Accumulate results
}
System.out.println(sb.toString()); // print final result
}
I do not know why you are trying to initialize int[] in a constructor and keep this array as a global variable when you said that 'method named output which will take an int array as a parameter'.
Here is a proper solution according to your requirements:
public static void main(String[] args) {
final int sizeOfArray = 10;
final int[] nums = new int[sizeOfArray];
//JAVA 7
for(int i = 0; i < sizeOfArray; i++){
nums[i] = (int)(Math.random() * 100) + 1;
}
//JAVA 8
IntStream.range(0,sizeOfArray)
.forEach(i -> nums[i] = (int)(Math.random() * 100) + 1);
output(nums);
}
private static void output(final int[] arrayToDisplay){
//JAVA 7
for(int i = 0; i < arrayToDisplay.length; i++){
System.out.printf("arr[%d] : %d \n",i,arrayToDisplay[i]);
}
//JAVA 8
IntStream.range(0,arrayToDisplay.length)
.forEach(i -> System.out.printf("arr[%d] : %d \n",i,arrayToDisplay[i]));
}
You should always make sure that all variables initialized and have an appropriate type assigned to them (at least in Java). If I were you, I would stick to Java 7 version of the code above
This problem won't be complied because there is not definition of what 'i' means in output method.
Another solution can be :
public String Output(){
StringBuffer sb = new StringBuffer();
int i=0;
while(i<nums.length){
sb.append("Arr[" + i + "]:" + nums[i]);
System.out.println(sb.toString());
sb.clear();
}
}
Related
This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 10 months ago.
I have an ArrayList and I'm trying to print it without the bracket ("[]") , I don't know where the problem lies , is it with how the ArrayList is initialized or is it the print method ?
The output that I'm getting :
S0 = (q0) = [0, 2]
S1 = (q1) = [1, 0]
S2 = (q2) = [2, 1]
The output that I'm trying to get :
S0 = (q0) = {q0, q2}
S1 = (q1) = {q1, q0}
S2 = (q2) = {q2, q1}
How can this be achieved ?
CODE :
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void printArray(String[][] data){
System.out.print(" ");
for (int i = 0; i < data[0].length; i++) {
System.out.print("q" + i + " ");
}
System.out.println();
for (int i=0;i< data.length;i++){
System.out.print("q" + i + " ");
for (int j=0;j< data[0].length;j++){
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static ArrayList findEpsilon(String[][] data){
ArrayList<ArrayList<Integer> > aList = new ArrayList<>();
ArrayList<Integer> a1;
for (int i = 0; i < data.length ; i++) {
a1 = new ArrayList<>();
//aList = new ArrayList<>();
a1.add(i);
for (int j = 0; j < data[0].length; j++) {
if (data[i][j].contains("eps")){
a1.add(j);
}
}
aList.add(a1);
}
return aList;
}
public static void printArrayList(ArrayList<ArrayList<Integer>> aList){
for (int i = 0; i < aList.size(); i++) {
for (int j = 0; j < aList.get(i).size(); j++) {
System.out.println("S" + j + " = (q" + j + ") = " + aList.get(i).get(j) + "
");
}
// System.out.println();
}
}
public static void main(String args[]) {
String[][] data = {
{ "a", "b", "eps"},
{ "eps", "a", "-" },
{ "a", "eps", "b"}};
ArrayList<ArrayList<Integer> > aList = new ArrayList<ArrayList<Integer> >(3);
printArray(data);
System.out.println("\n");
aList.add(findEpsilon(data));
printArrayList(aList);
}
}
The type of aList should be ArrayList<ArrayList<ArrayList<Integer>>>. The compiler doesn't complain about this because the findEpsilon method returns an ArrayList without type parameters. It's generally good practice to specify the generic type (i.e., findEpsilon should return ArrayList<ArrayList<ArrayList<Integer>>>). You will need to fix this in several places.
If you want to use curly brackets for the array, you can then use the following code:
for (int j = 0; j < aList.get(i).size(); j++) {
String listAsString = aList.get(i).get(j).stream().map(Object::toString).collect(Collectors.joining(",", "{", "}"));
System.out.println("S" + j + " = (q" + j + ") = " + listAsString + " ");
}
The stream iterates over each of the elements in the list and converts them to a string. The Collectors.joining collector then joins the individual strings by inserting a comma between them and placing curly brackets at the start and at the end.
You can define a Lambda to take a List<String> and convert it like you want.
put the list.toString version in a StringBuilder.
then change the first and last characters to { and } respectively
import java.util.function.Function;
Function<List<String>, String> fmt = lst-> {
StringBuilder sb = new StringBuilder(lst.toString());
sb.setCharAt(0,'{');
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
};
Now apply a list to the lambda.
List<String> s = List.of("A","B","C");
System.out.println(fmt.apply(s));
prints
{A, B, C}
So I am trying to complete this code. The goal is to input an array of strings, then count the frequency of how often the words are found. For example:
input:
joe
jim
jack
jim
joe
output:
joe 2
jim 2
jack 1
jim 2
joe 2
An array must be chosen for Strings, and another array much be chosen for word frequency.
My code so far:
I am stuck into trying to implement this. The string method is set, but how am I going to count the frequency of words, and also assign those values to an array. Then print both side by side. I do know that once the integer array is set. We can simply do a for loop to print the values together such as. System.out.println(String[i] + " " + countarray[i]);
public class LabClass {
public static int getFrequencyOfWord(String[] wordsList, int listSize, String currWord) {
int freq = 0;
for (int i = 0; i < listSize; i++) {
if (wordsList[i].compareTo(currWord) == 0) {
freq++;
}
}
return freq;
}
public static void main(String[] args) {
LabClass scall = new LabClass();
Scanner scnr = new Scanner(System.in);
// assignments
int listSize = 0;
System.out.println("Enter list Amount");
listSize = scnr.nextInt();
// removing line to allow input of integer
int size = listSize; // array length
// end of assignments
String[] wordsList = new String[size]; // string array
for (int i = 0; i < wordsList.length; i++) { //gathers string input
wordsList[i] = scnr.nextLine();
}
for (int i = 0; i < listSize; i++) {
String currWord = wordsList[i];
int freqCount = getFrequencyOfWord(wordsList, listSize, currWord);
System.out.println(currWord + " " + freqCount);
}
}
}
int some_method(String[] arr, String word) {
int count = 0;
for (int i=0; i<arr.size(); i++) {
if (arr[i].equals(word)) count++;
}
return count;
}
Then in main method:
String[] array = ["joe", "jake", "jim", "joe"] //or take from user input
int[] countArray = new int[array.size()]
for (int i=0; i<array.size(); i++) {
countArray[i] = some_method(array, array[i])
}
System.out.println(array[0] + " " + countArray[0]);
Ouput:
joe 2
import java.io.*;
import java.util.*;
public class chopMiddle {
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
}
}
I try to break the string into tokens and uses Integer.parseInt method to convert the tokens into int value.
I want to return an array of size 3 which contains the int values of the 2nd to the 4th integers from the string to the caller. Am i doing something wrong, because it shows below message when i compiled
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at chopMiddle.main(chopMiddle.java:18)
The problem will be when it gets to the 5th token, it will read it, then create a new array and try to read 3 more.
After you have read the 2nd, 3rd and 4th, you should break both loops.
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) //check hasMoreTokens
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
you need to check every time when you call: tokenizer.nextToken()
If you check if tokenizer has more elements in the for loop itself then you won't require while loop at all.
try below example :
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
int[] array = new int[3];
for (int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) {
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
I have a Array of strings and I want to get the number of characters in the particular element in the array of strings,how i can do that?
like a array arr have = {"abc", "bgfgh", "gtddsffg"}
if i use
a.length; I will get the 3 which is the no.of elements in array
but I want a method which when I apply on each element like
for(int = 0; ; i++)
{
int t = a[i].length; //this method doesn't work
}
to return the number of characters in each element
which is the given example has to be 3,5 and 8
PLEASE REPLY?
package stackoverflow.q_24933319;
public class FindLength {
public static void main(String[] args) {
String[] arr = {"abc","bgfgh","gtddsffg"};
System.out.println("Array size is: " + arr.length);
for(String s : arr) {
System.out.println("Value is " + s + ", length is " + s.length());
}
}
}
//Output:
//Array size is: 3
//Value is abc, length is 3
//Value is bgfgh, length is 5
//Value is gtddsffg, length is 8
Unlike arrays, String doesn't have an attribute length, but it has a method length() which returns the String's length (in Unicode code units, see JavaDoc).
Try this: a[i].length().
I think a good idea is to put numbers of characters into another table. If you want, you can after that make some other operation on each of this number outside the for loop.
String [] input = {"aaaa", "sdasdwdas", "sd"};
int [] output = new int [input.length];
for (int i = 0; i < input.length; i++)
output[i] = input[i].length();
I think this code has the answer to your question in at least one of the functions.
public int[] getEachLengthIndividually(String[] arr)
{
int[] retArray = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
String string = arr[i];
retArray[i] = string.length();
}
return retArray;
}
public int totalSize(String[] arr)
{
int totalSize = 0;
for(String string : arr)
{
totalSize += string.length();
}
return totalSize;
}
public static void main(String[] args)
{
String[] arr = {"abc", "bgfgh", "gtddsffg"};
int[] eachLengthIndividually = getEachLengthIndividually(arr);
int totalLength = getTotalLength(arr);
for(int i = 0; i < eachLengthIndividually.length; i++)
{
System.out.println("The string " + arr[i] + " at index " + i + " has length of " + eachLengthIndividually[i]);
}
System.out.println("The total length of all strings in the array is " + totalLength);
}
Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?
Only can use int, or int[].
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
System.out.println(reverseMe);
Output:
!em esrever
Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.
The objects of the Java String class are immutable - their contents cannot be altered after being created.
You will need at least two temporary objects - one for the final result and one for the intermediate values - even if you do find a way to avoid using a local variable.
EDIT:
That said, since you can use int[] you may be able to cheat.
Since char can be assigned to int, you can use String.charAt() to create an int array with the character values in reverse order. Or you may be allowed to use String.toCharArray() to get a char array that will be copied over to your int[] temporary.
Then you use the variable that holds the reference to your original string (or the result variable, if you are allowed one) to start from an empty string (easily obtainable with a direct assignment or String.substring()) and use String.concat() to create the final result.
In no case, however, will you be able to swap the characters in-place as you would do in C/C++.
EDIT 2:
Here's my version which does not use StringBuffer/Builders internally:
int r[] = new int[s.length()];
int idx = r.length - 1;
for (int i : s.toCharArray()) {
r[idx--] = i;
}
s = s.substring(0, 0);
for (int i : r) {
s = s.concat(String.valueOf((char)i));
}
String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
}
System.out.println(s); // !dlroW olleH
No temporary variables! :)
One of many ways:
String str = "The quick brown fox jumps over the lazy dog";
int len = str.length();
for (int i = (len-1); i >= 0; --i)
str += str.charAt(i);
str = str.substring(len);
System.out.println(str);
public String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
Because you can use an int, you can assign an int a char value:
String aString = "abc";
int intChar = aString.charAt(0);
You will have to convert from the int back to the char to assign it to aString.charAt(2).
I'm sure you can figure it out from there.
First append the string to itself in reverse manner. Then take the second half out of it.
public class RevString {
public static void main(String[] args) {
String s="string";
for(int i=s.length()-1;i>=0;i--){
s+=s.charAt(i);
}
s=s.substring(s.length()/2, s.length());
System.out.println(s);
}
}
Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:
public static void main(String[] args) {
String test = "Hello World";
String rev = "";
Pattern p = Pattern.compile("[\\w|\\W]");
Matcher m = p.matcher(test);
while (m.find()) {
rev = m.group()+rev;
}
System.out.println("Reverse==" + rev);
}
Output
Reverse==dlroW olleH
Hope it helps :)
public class Test {
static St`enter code here`ring reverseString(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (i == 0) {
str = str.charAt(str.length() - 1 - i) + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i);
} else {
str = str.substring(0, i) + str.charAt(str.length() - 1 - i)
+ str.substring(i + 1, str.length() - 1 - i) + str.charAt(i)
+ str.substring(str.length() - i, str.length());
}
}
return str;
}
public static void main(String args[]) {
String s = "ABCDE";
System.out.println(Test.reverseString(s));
}
}
String str = "Welcome";
for(int i=0;i<str.length();){
System.out.print(str.charAt(str.length()-1));
str = str.substring(0,str.length()-1);
}
Except for loop variables.
You can use class java.lang.StringBuilder:
String reservedString = new StringBuilder(str).reserve().toString();