I was wondering how can I use the remAll method on the very bottom of my code.
Whenever I try to use out.println(list.remAll());, it gives me an error saying
"No suitable method found for remAll"?
How can I fix this?
I have also tried using out.println(remAll(list));
I'm a beginner when it comes to Java and I am just learning, so pardon me if this is much simpler than it looks. P.S. Sorry if the format is wrong or something. It's my first post here.
import java.util.*;
import static java.lang.System.*;
public class StringArrayListLoader
{
public static void main(String args[])
{
Scanner kb = new Scanner(in);
out.print("Size of list? ");
int s = kb.nextInt();
ArrayList<String>list = new ArrayList<String>();
out.println("Enter the Strings: ");
for(int x = 0; x < s; x++)
{
out.print("String " + x + " :: ");
list.add( kb.next());
}
out.println("\nThe ArrayList you entered is ...");
out.println(list);
out.println(beginWithx(list) + " of the Strings begin with an \'x\'");
out.println(firstLast(list) + " of the Strings begin and end witletter.");
out.println("First String = Last String? " + firstLast2(list));
out.println(*******); // what am i supposed to put here?
}
public static int beginWithx(ArrayList<String>ar)
{
int count = 0;
for(int i = 0; i<ar.size(); i++)
if("x".equals(ar.get(i).substring(0,1)))
count++;
return count;
}
public static int firstLast(ArrayList<String>ar)
{
int counting = 0;
for(int i = 0; i<ar.size(); i++)
if(ar.get(i).substring(0,1).equals(ar.get(i).substring(ar.get(i).length()-2, ar.get(i).length()-1)))
counting++;
return counting;
}
public static boolean firstLast2(ArrayList<String>ar)
{
int counting = 0;
if(ar.get(0).equals(ar.get(ar.size()-1)))
return true;
return false;
}
public static void remAll(ArrayList<String>list, String s)
{
int i=0;
while(i<list.size())
{
if(list.get(i).equals(s))
{
list.remove(i);
}
else
{
i++;
}
}
out.println(list);
}
}
Your remAll method takes two parameters, an ArrayList<String> and a String. You must pass two parameters to call the method properly, such as
remAll(list, someOtherStringHere); // remAll has its own "out.println" calls
The method signature is
public static void remAll(ArrayList<String>list, String s)
So, you need to call it like:
remAll(list, "some string");
By inspection of the code, it will then remove all instances of "some string" from the list.
Related
i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();
So I'm writing a basic MasterMind game that is... mostly functional. However, its exhibiting odd behavior and I'm unsure why.
The idea is that what defines a Code and its behavior is one file, the gameplay is another, and the Main just creates a new game and starts playing. When I initialize the game, the computer creates a new random string of 4 (the "secret code"), as expected; but then once I get input for the User guess, it seems to rewrite the secret code into whatever I've input. Further, my methods for evaluating matches don't work at all, but considering that the secret code keeps changing means that it's not being set to begin with, and I'm unsure why.
All three classes below. Why is my class variable in Game not setting properly and accessible to the other methods?
Main.java
class Main {
public static void main(String[] args) {
Game newGame = new Game();
newGame.play();
}
}
Code.java
import java.util.Random;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Math;
import java.lang.StringBuilder;
class Code {
private static HashMap<String,String> PEGS;
private static ArrayList<String> pegStrings;
protected static String secretCodeString;
public static void main(String[] args) {
}
public Code(String input){
this.secretCodeString = input;
}
public Code(){
randomize();
}
//literally just creates the peghash
public static void setPegs(){
PEGS = new HashMap<String,String>();
PEGS.put("C","c");
PEGS.put("Y","y");
PEGS.put("R","r");
PEGS.put("P","p");
PEGS.put("O","o");
PEGS.put("G","g");
}
//turns the pegs ito something randomize can use
public static ArrayList<String> makePegArray(){
setPegs();
pegStrings = new ArrayList<String>();
Collection<String> pegValues = PEGS.values();
Object[] pegObjects = pegValues.toArray();
for (int i = 0; i < pegObjects.length; i++){
pegStrings.add(pegObjects[i].toString());
}
return pegStrings;
}
// sets Class Variable secretCode to a four letter combination
public static Code randomize(){
secretCodeString = new String();
Random rand = new Random();
int randIndex = rand.nextInt(makePegArray().size());
for (int i = 0; i < 4; i++){
randIndex = rand.nextInt(makePegArray().size());
secretCodeString = secretCodeString.concat(makePegArray().get(randIndex));
}
Code secretCode = parse(secretCodeString);
return secretCode;
}
public static Code parse(String input) {
setPegs();
makePegArray();
String[] letters = input.split("");
StringBuilder sb = new StringBuilder();
for (String letter : letters) {
if (pegStrings.contains(letter)) {
sb.append(letter);
} else {
System.out.println(letter);
throw new RuntimeException();
}
}
String pegListString = sb.toString();
Code parsedCode = new Code(pegListString);
//System.out.println(parsedCode);
return parsedCode;
}
public int countExactMatches(Code guess){
String guessString = guess.secretCodeString;
int exactMatches = 0;
String[] guessArray = guessString.split("");
String[] winningCodeArray = (this.secretCodeString).split("");
for(int i = 0; i < 4; i++){
if(guessArray[i] == winningCodeArray[i]){
exactMatches++;
}
}
return exactMatches;
}
public int countNearMatches(Code guess) {
String guessString= guess.secretCodeString;
HashMap<String,Integer> guessCount = new HashMap<String,Integer>();
HashMap<String,Integer> secretCodeCount = new HashMap<String,Integer>();
Set<String> codeKeys = guessCount.keySet();
int matches = 0;
int keys = guessCount.keySet().size();
String[] keyArray = new String[keys];
for(int i = 0; i < guessString.length(); i++) {
//removes character from string
String codeCharacter = String.valueOf(guessString.charAt(i));
String guessShort = guessString.replace(codeCharacter,"");
//counts instances of said character
int count = guessString.length() - guessShort.length();
guessCount.put(codeCharacter, count);
}
for(int i = 0; i < secretCodeString.length(); i++) {
//removes character from string
String winningString = this.secretCodeString;
String winningCodeCharacter = String.valueOf(winningString.charAt(i));
String winningCodeShort = guessString.replace(winningCodeCharacter,"");
//counts instances of said character
int count = winningString.length() - winningCodeShort.length();
secretCodeCount.put(winningCodeCharacter, count);
}
for (int i = 0; i < keys; i++) {
codeKeys.toArray(keyArray);
String keyString = keyArray[i];
if (secretCodeCount.containsKey(keyString)) {
matches += Math.min(secretCodeCount.get(keyString), guessCount.get(keyString));
}
}
int nearMatches = matches - countExactMatches(guess);
return nearMatches;
}
}
Game.java
import java.util.Scanner;
class Game {
protected static Code winningCode;
public static void main(String[] args){
}
public Game(){
winningCode = new Code();
}
protected static Code getGuess() {
Scanner userInput = new Scanner(System.in);
int count = 0;
int maxTries = 5;
while(true){
try {
String codeToParse = userInput.next();
Code guess = Code.parse(codeToParse);
return guess;
} catch(RuntimeException notACode) {
System.out.println("That's not a valid peg. You have " + (maxTries - count) + " tries left.");
if (++count == maxTries) throw notACode;
}
}
}
protected static void displayMatches(Code guess){
int nearMatches = winningCode.countNearMatches(guess);
int exactMatches = winningCode.countExactMatches(guess);
System.out.println("You have " + exactMatches + " exact matches and " + nearMatches + " near matches.");
}
protected static void play(){
int turnCount = 0;
int maxTurns = 10;
System.out.println("Greetings. Pick your code of four from Y,O,G,P,C,R.");
while(true){
Code guess = getGuess();
displayMatches(guess);
if (guess == winningCode) {
System.out.print("You win!!");
break;
} else if (++turnCount == maxTurns) {
System.out.print("You lose!!");
break;
}
}
}
}
On every guess, you call Code.parse, Code.parse creates a new Code (new Code(pegListString);) and that constructor sets the secretCodeString and because that's static, all instances of Code share the same variable. You need to avoid mutable static members.
Another tip is to either have a method return a value, or mutate state (of either its input, or its own instance, this), but avoid doing both.
"Why is my class variable rewriting itself after an unrelated method runs?"
Because, actually, it is not unrelated. The "mess" that you have created by declaring variables and methods as static has lead to unwanted coupling between different parts of your code.
It is difficult to say what the correct solution is here because your code has gotten so confused by the rewrites that it is hard to discern the original "design intent".
My advice would be to start again. You now should have a clearer idea of what functionality is required. What you need to do is to redo the object design so that each class has a clear purpose. (The Main and Game classes make sense, but Code seems to be a mashup of functionality and state that has no coherent purpose.)
I am currently getting error code
TOOLS.java:48: error: incompatible types: ToolItem[] cannot be converted to int[]
when running this program that extends from a .class.
The issue is with the line
int indEX = SearchArray(toolArray, srchnum);
I'm not sure what the issue is. The only thing I can think of is toolArray contains information about tools from the ToolItem class, which has Strings as well as integers and doubles, for storing tool information like name/ID/quantity etc. I'm not sure where I went wrong. I can post the .class if needed
public class TOOLS extends ToolItem
{
// Private members
private int numberOfItems;
private ToolItem[] toolArray = new ToolItem[10];
Scanner keyboard = new Scanner(System.in);
public TOOLS()
{
int numberOfItems = 0;
for (int i=0; i<10; i++)
toolArray[i] = new ToolItem();
}
// search method
public static int SearchArray(int[] toolArray, int srchnum)
{
int i=0;
while (i < toolArray.length)
{
if (toolArray[i] == srchnum)
return i;
else
i++;
}
return -1;
}
// calling search method
public void main(String[] args)
{
int srchnum;
System.out.println("Enter a toolID to search: ");
srchnum = keyboard.nextInt();
int indEX = SearchArray(toolArray, srchnum);
if (indEX == -1)
System.out.println(" " + srchnum + "No ID match");
else
System.out.println(" " + srchnum + "was found at " + indEX);
}
}
Well you declared private ToolItem[] toolArray = new ToolItem[10]; but you're calling a function that asks for an int array:
public static int SearchArray(int[] toolArray, int srchnum)
Based on your code it would seem that you're trying to search by index in the array? You could change the parameter of the function you're calling and then use the getIndex() method on the specified array to compare the index with the srchnum.
//Changed first parameter type
public static int SearchArray(ToolItem[] toolArray, int srchnum)
{
int i=0;
while (i < toolArray.length)
{
//Get the index of the toolArray at position 'i'
if (toolArray[i].getIndex() == srchnum)
return i;
else
i++;
}
return -1;
}
public class ArrayMethodsTest
{
public static void main(String[] args)
{
int[] tester = {0,1,2,3,4,5};
ArrayMethods test = new ArrayMethods(tester);
for(int element : test)
{
System.out.print(element + " ");
}
test.shiftRight();
for(int element : test) //error: for-each not applicable to expression type
{
System.out.print(element + " ");
}
}
}
I figure what the problem is. Thanks to jigar joshi. However I still need to use the ArrayMethods methods for the tester that I created. I know that they work but how can it be possible to provide a tester class for an object that isn't an array since the methods are for arrays.
public class ArrayMethods
{
public int[] values;
public ArrayMethods(int[] initialValues)
{
values = initialValues;
}
public void swapFirstAndLast()
{
int first = values[0];
values[0] = values[values.length-1];
values[values.length-1] = first;
}
public void shiftRight()
{
int first = 0;
int second = first;
for(int i =0; i < values.length; i++)
{
if(i < values.length-1)
{
first = values[i];
second = values[i+1];
values[i+ 1] = first;
}
if(i == values.length)
{
values[i] = values[0];
}
}
}
}
//0,1,2,3,4,5
//5,0,1,2,3,4
test is reference of ArrayMethods which is not an Iterable or an array type and so is the error
You've already encountered the issue in which you can't iterate over an ArrayMethods, since it's not iterable. What it seems like you want to do is iterate over its values instead, considering that values is a public field.
for(int element : test.values) {
System.out.print(element + " ");
}
I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].