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);
}
}
Related
I am writing a program that takes in the number of ingredients. The prog
This is my code:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);:
public static void sortCalories(double[] calories,double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p=0; p<calories.length; p++) {
for (int j=p+1; j<calories.length; j++) {
if(calories[p]/price[p]>calories[j]/price[j]) {
temp = calories[p];
calories[p] = calories[j];
calories[j] = temp;
temp = price[p];
price[p] = price[j];
price[j] = temp;
temp1 = ingredientName[p];
ingredientName[p] = ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}
I am trying to load data from a txt file and it will only read one line of the txt file. When I specify what the int I variable is in my for loop within my loadData method it will print that particular line. I am not sure why it won't just add and print all my data.
I tried using an outer for loop to see if would print and add the data that way, but no luck
import java.io.*;
import java.util.*;
public class BingoSortTest
{
static BingoPlayer [] test;
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
test = new BingoPlayer [10];
loadData();
System.out.print(Arrays.toString(test));
}
public static void loadData() throws IOException
{
Scanner S = new Scanner(new FileInputStream("players.txt"));
double houseMoney = S.nextDouble();
S.nextLine();
int player = S.nextInt();
S.nextLine();
for(int i = 0; i < test.length; i++)
{
String line = S.nextLine();
String [] combo = line.split(",");
String first = combo [0];
String last = combo [1];
double playerMoney = Double.parseDouble(combo[2]);
BingoPlayer plays = new BingoPlayer(first, last, playerMoney);
add(plays);
}
}
public static void add(BingoPlayer d)
{
int count = 0;
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
}
Here is the contents of the txt file I am using:
50.00
10
James,Smith,50.0
Michael,Smith,50.0
Robert,Smith,50.0
Maria,Garcia,50.0
David,Smith,50.0
Maria,Rodriguez,50.0
Mary,Smith,50.0
Maria,Hernandez,50.0
Maria,Martinez,50.0
James,Clapper,50.0
Every Time you put a BingoPlayer at Index 0 .
public static void add(BingoPlayer d)
{
int count = 0; // <-------------------- Here
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
you have to define static counter variable where array of BingoPlayer is defined.
define count variable static
static BingoPlayer [] test;
static int count = 0;
and chane the add function definition like this.
public static void add(BingoPlayer d)
{
if (count< test.length) {
test[count] = d;
count++;
}
else
System.out.println("No room");
}
I am trying to create a method that counts the number of times a specified character appears in a given string, by printing the sentence and the specified character and its count.
This is what I have completed so far:-
import java.util.Scanner;
public class Program4 {
public int count ( String sentence, char letter)
{
int times = 0;
for (int x=0;x<sentence.length();x++)
{
if (sentence.charAt(x) ==letter){times++;}
}
return times;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
}
program4.count("Hello World",'o');
scan.close();
}
}
I understand I need a "system.output.println" but I don't know what value goes inside to get the output I am looking for. I would appreciate any help, I am beginner with java. Thank you.
it works, you had compile time error in code
import java.util.Scanner;
public class Program4 {
public int count(String sentence, char letter) {
int times = 0;
for (int x = 0; x < sentence.length(); x++) {
if (sentence.charAt(x) == letter) {
times++;
}
}
return times;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Program4 program4 = new Program4();
int timesCount = program4.count("Hello World", 'o');
System.out.println("count is :" + timesCount);
scan.close();
}
}
Below is some code that tries to find the first word above a certain amount of characters.
public class FirstMatch {
public static void main(String[] args) throws java.io.FileNotFoundException {
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
String longWord = "";
boolean found = false;
public void threshold (int Threshold) {
while (in.hasNext() && !found) {
String word = in.next();
if (word.length() > Threshold) {
longWord = word;
found = true;
}
}
System.out.println("The first long word is: " + longWord);
}
}
}
(In the above code I didn't copy in all the import statements)
For some reason for my threshold method it returns illegal start of expression. I think it is a stupid mistake but can't figure out what's wrong...
You should declare your threshold method out of the main method.
A method can only be created at class level, and not inside another method.
import java.io.FileReader;
import java.util.Scanner;
public class FirstMatch {
public static void main(String[] args) throws java.io.FileNotFoundException {
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
threshold(in, 10);
}
public static void threshold(Scanner in, int threshold) {
String longWord = "";
boolean found = false;
while (in.hasNext() && !found) {
String word = in.next();
if (word.length() > threshold) {
longWord = word;
found = true;
}
}
System.out.println("The first long word is: " + longWord);
}
}
Fixed it. Working code! I had to move the fruit array into the method and call it from main.
import java.util.Scanner;
public class StringArrayTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input;
System.out.println("Enter a fruit: ");
input = sc.nextLine();
System.out.println("Is \"" + input + "\" in the array? " + isIn(input));
sc.close();
}
public static boolean isIn(String input) {
String[] fruit = new String[6];
fruit[0] = "grape";
fruit[1] = "banana";
fruit[2] = "apple";
fruit[3] = "mango";
fruit[4] = "watermelon";
fruit[5] = "orange";
for(int i = 0; i < fruit.length; i++) {
if (input.equals(fruit[i])) {
return true;
}
}
return false;
}
}
The following code will return true if the array contains the input and false if it doesn't.
Credits to camickr for this code:
Arrays.asList(yourArray).contains(yourString)
return false must be outside the for loop. If it's in the else part, the for loop will end at the first iteration.
Here's how the code should look like:
public boolean isIn(String input) {
for(int i = 0; i < fruit.length; i++) {
if (input.equals(fruit[i])) {
return true;
}
}
return false;
}
Also, you cannot declare a method inside another method. Move the method isIn outside main.
Other problems in your code:
String[] fruit is currently declared, initialized and filled inside main method. It should be at least declared outside as a field of the class in order to be accessed by other methods.
You're not using isIn anywhere.
In order to use the fields and methods inside main method, you have two options:
Declare the fields and methods as static.
Create a new instance of your class inside the main method and use the fields and methods from this instance.
The code may look like this:
import java.util.Scanner;
public class StringArrayTest {
static String[] fruit = new String[6];
public static void main(String[] args) {
fruit[0] = "grape";
fruit[1] = "banana";
fruit[2] = "apple";
fruit[3] = "mango";
fruit[4] = "watermelon";
fruit[5] = "orange";
Scanner sc = new Scanner(System.in);
String input;
input = sc.nextLine();
if (isIn(input)) {
//do something...
} else {
//do something else...
}
}
public static boolean isIn(String input) {
for(int i = 0; i < fruit.length; i++) {
if (input.equals(fruit[i])) {
return true;
}
}
return false;
}
}
Summarizing the suggestions given by others.
import java.util.Arrays;
import java.util.Scanner;
public class StringArrayTest {
public static void main(String[] args) {
String[] fruit = new String [] {"grape", "banana", "apple", "mango", "watermelon", "orange"};
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println(Arrays.asList(fruit).contains(input));
}
}