random Strings in ArrayList - java

I bought Head First Java book, and i am trying to do the exercise sink a startup.
After a while the book introduce ArrayList, and show how to use it in the class and its' method.
Problem is once i change everything with arraylist, the MAIN doesn't work, becasue at start i used simple INT, in the array location, now it need array.
How can i change the values of INT into a type that i can put inside the array ?
thx for help, and here the code.
the class with the method:
private ArrayList<String> locationCells;
private int numOfHits = 0;
public void setLocationCells(ArrayList<String> locationCells)
{
this.locationCells = locationCells;
}
public String checkYourself(String guess) {
// creazione stringa miss
String result = "miss";
int index = locationCells.indexOf(guess);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
numOfHits ++;
}else
result = "hit";
System.out.println(result);
return result;
}
and here the MAIN:
public static void main(String[] args) {
java.util.Random randomGenerator = new java.util.Random();
Scanner scan = new Scanner(System.in);
StartUpCorretta dot = new StartUpCorretta();
int manyGuesses = 0;
boolean isAlive = true;
int randomNumbers = randomGenerator.nextInt(5) +1;
int randomNumb = (int) (Math.random() * 5);
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
dot.setLocationCells(location);
while(isAlive) {
System.out.println("enter a number");
int guess = scan.nextInt();
String result = dot.checkYourself(guess);
manyGuesses ++ ;
if (result.equals("kill")) {
isAlive = false;
System.out.println("you took" + " " + manyGuesses + " " + "guesses");
}
}
}

Seems, you are taking your input from console as int from this statement
int guess = scan.nextInt();
So, my answer is based on your input data type.
Please, changed your arraylist generic type String to Integer
And Secondly, this is not how you can initialized the arraylist
ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};
Correct way to create collection using new operator like this
ArrayList<Integer> location = new ArrayList<>();
and correct way to add element into arraylist like this
location.add(randomNumbers);
location.add(randomNumbers+1);
location.add(randomNumbers+2);
Hope, it will work for you.

Related

I am building a calculator, the user enters something similar to this: 3+2*7/4 and the code calculate it.However i have a big problem with the indexes

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Model {
private ArrayList<String> num = new ArrayList<>();
private ArrayList<String> op = new ArrayList<>();
private ArrayList<String> num1 = new ArrayList<>();
private ArrayList<String> op1 = new ArrayList<>();
private Scanner sc = new Scanner(System.in);
private ArrayList<String> ope = new ArrayList<>();
private ArrayList<Double> nume = new ArrayList<>();
public Model()
{
}
public void split()
{
String exp= sc.next();
String num[]= exp.split("[/+/*/-]");
String op[]= exp.split("[0123456789]");
for(String x : num)
{
this.num.add(x);
this.num1.add(x);
}
for(int i =1; i<op.length; i++)
{
this.op.add(op[i]);
this.op1.add(op[i]);
}
}
public void precedence_work()
{
for(int i=0; i <op.size();i++)
{
String num = "";
if(this.op.get(i).equals("*")||this.op.get(i).equals("/"))
{
extra_split(i);
num = calculate_split();
this.op1.remove(i);
this.num1.set(i, num);
this.num1.remove(i+1);
System.out.println(i + " loop debug");
}
}
for(int i=0; i <3;i++)
{
extra_split(i);
String num = calculate_split();
this.op1.remove(i);
this.num1.set(i, num);
this.num1.remove(i+1);
}
System.out.println(num);
}
private void extra_split(int index)
{
ope.add(this.op.get(index));
nume.add(Double.parseDouble(num.get(index))); //specifying the needed high precedence expression to be worked on
nume.add(Double.parseDouble(num.get(index+1)));//by putting them ina specific arraylist to make stuff easier to work with
}
private String calculate_split()
{
double num = 0;
if(ope.get(0).equals("*") )
{
num = nume.get(0)*nume.get(1);
System.out.println(num);
}
else if(ope.get(0).equals("/") )
{
num = (nume.get(0))/(nume.get(1));
}
else if(ope.get(0).equals("+") )
{
num = nume.get(0)+nume.get(1);
}
else if(ope.get(0).equals("-") )
{
num = nume.get(0)-nume.get(1);
}
else
System.out.println("Error!");
System.out.println("Nume before, debug:" + nume);
System.out.println("Ope before, debug:" + ope);
this.ope.remove(0);
this.nume.remove(nume.get(0));//because whenever i put index 0 or index 1, it is giving error but somehow this works
this.nume.remove(nume.get(0));
System.out.println("Nume after, debug:" + nume);
System.out.println("Ope after, debug:" + ope);
return Double.toString(num);
}
}
I tried playing a lot around indexes, making the arraylist having the values but opposite then I use the index in a decrementing manner but it still did not work, and I did other ways but they did not make any sense but I was just hoping they work.
Explanation of the code: the algorithm i am trying to do is the following
User enters: 1+32-35
Split the operators and numbers and put them in different arraylist
num arraylist [1, 3, 2, 3 , 5]
operator arraylist[+, *, -, *]
look at the op and num arraylist , you will realize that if "*" is index 1 in op arraylist then the number supposedly to be before it is index 1 in the num arraylist and the number after it is index 1 +1 = 2
so 32 but to make the code easier to calculate, i put that two specific numbers with the following operator in a different arraylist nume and ope, so when i am working on this nummber the nume is [3,2] ope[] however after finishing from calculating this, the arraylist is reset in order for the next expression to be worked on`

Java int error cant be int[]

Hey i get the following error int cant be int[] i dont understand it :I
Error is on
int[] cijferStudent = new int [7]; and in the while loop. If someone can help me i will appreciate it.
Thanks you for your help :)
package oefenopdracht6a;
import java.util.Scanner;
/**
*
* #author eazyman
*/
public class Oefenopdracht6a {
public static Scanner input = new Scanner(System.in);
public static int aantalCijfers = 0;
public static void main(String[] args) {
aantalCijfersGeroepen();
}
public static void aantalCijfersGeroepen() {
System.out.println("Hoeveel cijfers wilt u invoeren?");
aantalCijfers = input.nextInt();
for (int i = 0; i >= aantalCijfers;) {
System.out.println("Aantal cijfers moet groter zijn dan 0!");
aantalCijfersGeroepen();
}
int i = 0;
int[] cijferStudent = new int[7];
while (i < aantalCijfers) {
System.out.println("Cijfer student " + i);
cijferStudent = input.nextInt();
i++;
}
System.out.println(cijferStudent);
}
}
cijferStudent = input.nextInt();
should be changed to
cijferStudent[i] = input.nextInt();
The error is because input.nextInt() will return an int, but cijferStudent is an array of int, so you cannot assign an intto int[]. However, you can assign an int to a particular location inside the array (which in this case I am guessing would be the ith location).
Besides the missing index, for every negative value the users enters
aantalCijfersGeroepen will be called, and coming back on a positive number hence N times the array asked to input. So split asking and handling.
public static void main(String[] args) {
aantalCijfersGeroepen();
uitgaveAantalCijfers();
}
public static void aantalCijfersGeroepen() {
System.out.println("Hoeveel cijfers wilt u invoeren?");
aantalCijfers = input.nextInt();
while (aantalCijfers <= 0) {
System.out.println("Aantal cijfers moet groter zijn dan 0!");
aantalCijfersGeroepen();
}
}
public static void uitgaveAantalCijfers() {
int[] cijferStudent = new int[7];
for (int i = 0; i < aantalCijfers; ++i) {
System.out.println("Cijfer student " + i);
cijferStudent[i] = input.nextInt();
//System.out.println(" " + cijferStudent[i]);
}
System.out.println(Arrays.toString(cijferStudent));
}
Also the printing of an array must either be done in a loop too,
or use the handy function Arrays.toString.

About generating unique random numbers

public String generateCustomerID(String id, int digit)//Customer Class
randomGenerator = new Random();
String index = "";
for(int i = 1; i <= digit; i++)
{
index += randomGenerator.nextInt(10);
}
return id + index;
public void storeCustomer(Customer customer)//Shop Class
{
customerList.add(customer);
HashSet<String> set = new HashSet<>();
String number = customer.generateCustomerID("AB", 1);
set.add(number);
customer.setCustomerID(number);
}
How can i make sure that only customers with unique id are stored. For example, if customer A got id "AB-1", then customer B should have a different id like "AB-8". I tried to use Hashset but but i am not sure this is the right method to solve this problem. I do not think i need to use UIDD.
consider this solution
static Set<String> taken = new HashSet <>();
public static void main(String [] args)
{
Scanner scan = new Scanner (System.in);
while (true) {
System.out.println("enter id ");
String id = scan.nextLine();
if (taken.contains(id)) {
System.out.println("already taken");
continue;
}
taken.add (id);
System.out.println("another [y/n]? ");
if (scan.nextLine().equals("n"))
break;
}
}
the key point being that set is a field and it is checked using contains
place
while(set.contains(number)){
number = customer.generateCustomerID("AB", 1);
}
before
set.add(number);customer.setCustomerID(number);

Error message when searching an array, incompatible data types

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

Java arraylist. I need to pass random numbers to an array list and pass them to another class to check those numbers against another set of numbers

I am confused with passing ARRAYLIST values from one class to another.
I used the ARRAY in these classes before. I am changed those with ARRAYLISTS.
I have 2 classes. this class has an ARRAYLIST called "locationcells". This programs get 3 random digits from another class and get uses inputs and check if their inputs match the 3 digits. it's more like a guessing game.
import java.util.ArrayList;
class SimpleDotCom {
private ArrayList<String> locationcells;
public void setLocationcells(ArrayList<String> Locs)
{
locationcells = Locs;
}
public String CheckYourself(String StringGuess)
{
String result = " Miss";
int index = locationcells.indexOf(StringGuess);
if (index >= 0)
{
locationcells.remove(index);
if (locationcells.isEmpty())
{
result = "Kill";
}
else
{
result = "Hit";
}
}
return result;
}
}
this looks right.
Now the class with the main method:
import java.util.ArrayList;
class SimpleDotComGame {
public static void main(String[] args)
{
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
/*
this is the part I don't understand. I used to have the int array and generated random numbers and it worked well.
int randomNum = (int) (Math.random() * 5);
ArrayList<String> locations = new ArrayList<String>();
*/
theDotCom.setLocationcells(locations);
boolean isAlive = true;
while (isAlive == true)
{
String guess = helper.getUserInput("Enter a number");
String result = theDotCom.CheckYourself(guess);
numOfGuesses++;
if (result.equals("Kill"))
{
isAlive = false;
System.out.println("You took " + numOfGuesses + "guesses");
}
}
}
}
If you see the comments section above. That's the part I am getting confused. I used to have an array there. INT array. So I was able to pass the INT random numbers to the "simpledotcom" class. Now it is an arraylist with string type, I am not sure how to move forward.
Thank you all in advance,
int numericGuess = Integer.parseInt(helper.getUserInput("Enter a number"));
Also you can use a list of Integers too:
ArrayList<Integer> locations = new ArrayList<Integer>();
while(//condition){
int randomNum = (int) (Math.random() * 5);
locations.add(randomNum)
}
this way you can perform
locations.indexOf(numericGuess) or locations.contains(numericGuess)
OR
Conversely you can do,
String guess = helper.getUserInput("Enter a number");
ArrayList<String> locations = new ArrayList<String>();
while(//condition){
int randomNum = (int) (Math.random() * 5);
locations.add(String.valueOf(randomNum))
}
and check by
locations.indexOf(guess) or locations.contains(guess)
You can always transform the random int to a string by using Integer.toString() before inserting into your array list.
You can convert the String back to int using Integer.parseInt()
E.g.
for (int i = 0 ; i < 3 ; i++)
{
locations.add(Integer.toString((int)(Math.random() * 5));
}
If I understand well: add 3 Strings to the ArrayList:
ArrayList<String> locations = new ArrayList<String>();
for (i=0; i<3; i++)
{ locations.add(String.valueOf((int) (Math.random() * 5))); }
Anyway, you might refactor a little as well, starting with the extracting the above lines from the main method.
Another way might be to store your integer in a list, and convert the guesses to integers. Looks more logic to me anyway. In that case, you'll have an ArrayList. To convert a string to an integer:
int guessNumber = Integer.parseInt(guess);
or
Integer guessNumber = Integer.valueOf(guess);
Both will throw a NumberFormatException if 'guess' does not contain a parseble integer (see javadoc )
Why are you not using arrays like (apparently) you did before, by the way?

Categories

Resources