Correct Output for java method - java

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();
}
}

Related

Running into wedge2: exit code for process is 1 error

I keep running into the same complier error in my program. Any ideas on what is stopping the program from compiling. The error I recieve is ----jGRASP wedge2: exit code for process is 1.
import java.util.Scanner;
public class CheckerboardV1
{
static Scanner keyboard = new Scanner(System.in);
static final char FULL_CHAR = '*';
static final char EMPTY_CHAR = '-';
public static void main(String[] args)
{
System.out.println("Checkerboard Version 1 ...");
System.out.print("Enter size:>");
int size = keyboard.nextInt();
row(size);
}
public static int row(int size)
{
for(int i=0;i<size;i++) //How Deep
{
for(int n=0;n<4;n++) //Fills one line
{
for(int m=0;m<size;m++) //Empty Characters
{
System.out.print(EMPTY_CHAR);
}
for(int m=0;m<size;m++)
{
System.out.print(FULL_CHAR); //Full Characters
}
}
System.out.println(); //Starts new Line
return size;
}
}
}

How to fix my my loadData method with my main class

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");
}

Assign new value to an Array using Enhanced For Loop

I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.
Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}

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