Java Error; array required, but java.lang.String found - java

I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}

Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.

The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";

Related

why I am getting ArrayIndexOutOfBoundsException?

Hi I am unable to know what I am doing wrong.
I have a string which is pass as an argument to a my class.
I have to split that string and assign the respective values to the member variable but it is not working properly.
Here is my class.
package virtusa;
public class pratice {
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public pratice()
{
}
public pratice(String rawInput)
{
temp = rawInput.split("$$##",2);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity =Integer.parseInt( temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
}
here is my main class
package virtusa;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String stub = in.nextLine();
pratice temp = new pratice(stub);
System.out.println(temp.getName);
System.out.println(temp.getQuantity);
System.out.println(temp.getPrice);
}
}
My Input = apple$$##12.5$$##9
error i am having -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at virtusa.pratice.<init>(pratice.java:17)
at virtusa.demo.main(demo.java:12)
String::split take regex as a parameter, so the $ has special meaning. You will need to escape it with a \
One of problems in your code in not escaping special characters as some comments are mentioning. In my opinion clearest solution is to use Patter quote
rawInput.split(Pattern.quote("$$##"), 3);
Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]
So the final code should look something like this
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public Practice() {
}
public Practice(final String rawInput) {
temp = rawInput.split(Pattern.quote("$$##"), 3);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity = Integer.parseInt(temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}

Arrays of Object test but not getting any output

I would like some guidance on this particular code that I am testing but currently it is not printing out anything and on top of that I feel as if it isn't reading the text file at all. It seems to finish right away with no errors and I only get prompted that "build is successful."
The assignment is to read from a data text file that list 20 lines of student information, each line is comprised of first name, last name, and their grade all seperated by spaces. I am put to it into an array and output their information, but for now I am testing to see if it will output the first name before I proceed.
public class studentClass {
private String studentFName, studentLName;
private int testScore;
private char grade;
//constructor
public studentClass(String stuFName, String stuLName, int stuTestScore){
studentFName = stuFName;
studentLName = stuLName;
testScore = stuTestScore;
}
public String getStudentFName(){
return studentFName;
}
public String getStudentLName(){
return studentLName;
}
public int getTestScore(){
return testScore;
}
public char getGrade(){
return grade;
}
public void setStudentFName(String f){
studentFName = f;
}
public void setStudentLName(String l){
studentLName = l;
}
public void setTestScore(int t){
if (t>=0 && t<=100){
testScore = t;
}
}
public void setGrade(char g){
grade = g;
}
}
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
for(int i = 0; i>studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
public static studentClass[] readStudentData(studentClass[] studentObject)throws IOException{
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String lines = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((lines = br.readLine()) != null){
String stuArray[] = lines.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
return studentObject;
}
You need to actually call the method to read in the data. Try the following (note I didn't handle the Exception. I leave that as an exercise to you)
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
//NOTE I CHANGED THE '>' TO '<'
for(int i = 0; i < studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
//Note that I changed the return type to void
public static void readStudentData(studentClass[] studentObject)throws IOException{
//Your code here
You'll see I changed your readStudentData to return void since you're passing the array into the method you don't need to return it. You'll need to remove the return at the end of it.
You could also leave it as a method returning a studentClass[] and have no parameters. Instead, create the studentClass array inside readStudentData. I would recommend that approach because it removes the need to create and pass the array, which complicates your main method.

Why this method doesn't return the value

public class Main {
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(tex));
reader.close();
}
public static int calculateCharacters(String text, int tex){
tex = text.length();
return tex;
}
}
So I receive a string from String text, then I send it to the method to calculate it's length and return a number which should be intercepted by System.out.println(calculateCharacters(tex)); and the probram should show me the number of letters in the string that was entered, the problem is: nothing reaches System.out.println(calculateCharacters(tex)); why ? where is this return tex; returning it then ?
Well I'm not entirely sure why you've got an int texvariable, but removing it lets this work perfectly. Try rewriting your method:
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
or if you're ready to be snazzy:
public static int calculateCharacters(String text) {
return text.length();
}
Java is pass-by-value (Is Java "pass-by-reference" or "pass-by-value"?), so keeping an extra int in there that you only use to store things locally won't actually change your value of tex.
Also, you instantiate the String text, but then pass tex to calculateCharacters(). Since you haven't created a texvariable before this, your compiler doesn't know what to pass to calculateCharacters(). Try changing that to:
System.out.println(calculateCharacters(text));
instead.
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(text));
reader.close();
}
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
}
It works
For counting the string use below code...
public class Main {
static int stringCount;
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
calculateCharacters(text);
System.out.println(stringCount);
reader.close();
}
public static int calculateCharacters(String text){
stringCount = text.length();
return stringCount;
}
}

subroutine taking an array as a parameter in Java

In the following program, the user is supposed to enter a String (name of a City) and the program should return the index of the corresponding City in the array.
But I get an error, in the subroutine indexCities the following message:
"nameCity cannot be resolved".
I guess it is a problem of variable scoping but I don't figure out how I should do.
Thanks for your help.
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities);
}
public static int indexCities(String cities[]) {
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
nameCity is a local variable inside your main method. You can not access it outside the method.
One option for you is to pass the nameCity also as an argument in indexCities method. Also return type of your indexCities method should be void since you are not returning anything.
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities, nameCity);
}
public static void indexCities(String cities[], String nameCity){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
You could do it in this way:
public static void main(String[] args) {
String cities[] = { "Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans" };
int index = indexCities(cities, "Vierzon");
System.out.println("Index of city Vierzon is: " + index);
}
public static int indexCities(String cities[], String cityName) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(name);
}
Scope of variable nameCity is limited to main function. You can not access it outside of main function.
The variable is out of scope when you try to use it inside the method indexCities. One solution is making the variable nameCity an instance variable by moving it's definition out of the main method, but your code can be improved in several ways too. Check some option below:
This will print the index of the city you're looking for inside the array:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(nameCity, cities);
}
public static void indexCities(String copyOfNameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(copyOfNameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
You you can improve it by making the method return a value. Like this:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "City found in index " + cityIndex);
}
public static int indexCities(String nameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
return i;
}
}
return -1;
}
}
Another way is:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
String cities[] = {"Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans"};
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city to be searched -> ");
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "Found at position " + cityIndex);
input.close();
}
public static int indexCities(String cityName, String cities[]) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(cityName);
}
}

Beginner; Methods and Strings

Here is the code:
import java.util.Scanner;
public class sending {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(first);
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(String first, String second){
first = ("Give me a number and I run down and add five to it");
second = ("Lol");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}
As you can see I am new to this and I am having a problem with the main method and the method giveMe.
I want to have giveMe work as a collection of strings that I can call when I need them.
But when I try the above example I eclipse tells me that "first cannot be resolved to a variable" on line six String text = giveMe(first);
What am I doing wrong?
You are trying to use an enum and you never declared one... declare your enum like this outside your Main.
enum s {FIRST, SECOND} //add this
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe(s.FIRST); //add the s. so it knows to use your enum
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
Then you want to modify your method to take an enum instead like this
public static String giveMe(s string) {
switch (string) {
case FIRST:
return "Give me a number and I run down and add five to it";
case SECOND:
return "Lol";
}
return "invalid string";
}
Beginner, your problem is resolved.
Firstly declaration is important in java. "First" variable is not intailzed in your block of code. Ideally it is not necessary for your scenario.
Try this
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String text = giveMe();
System.out.println(text);
int x = scanner.nextInt();
x = number(x);
skrivUt(x);
}
//method for printing on screen
public static String giveMe(){
String first = ("Give me a number and I run down and add five to it");
return first;
}
//method for doing math
public static int number(int x){
x = x + 5;
return x;
}
//method for printing out
public static void skrivUt(int x){
System.out.println(x);
}
}

Categories