I'm traying to create x amount of arrays, each one called square(number)=new Array....
int numberofsquares=1;
int prgrm=0;
int amount=0;
int v=1;
while(prgrm==0) {
System.out.println("Enter another square? (y/n)");
if (stdin.next().startsWith("y")) {
List<String> square(x) = new ArrayList<String>();
while(amount!=3)
{
System.out.println("Enter: ");
square(x).add("1,"+v+","+stdin.next());
v++;
amount++;
System.out.println(firstsquare);
}
amount=0;
v=1;
while(amount!=3)
{
System.out.println("Enter: ");
square(x).add("2,"+v+","+stdin.next());
v++;
amount++;
System.out.println(firstsquare);
}
amount=0;
v=1;
while(amount!=3)
{
System.out.println("Enter: ");
square(x).add("3,"+v+","+stdin.next());
v++;
amount++;
System.out.println(firstsquare);
}
amount=0;
v=1;
} else {
prgrm++;
}
}
if (prgrm==1) {
System.out.println("Finish");
}
So the first time you press y the array that creates is called square1, the next one square2,squre3...
How can I do this? Thanks :D
No, You can't create variable names dynamically.
But if your intention is to create different storage space then you can use List<List<String>>(as mentioned already) and can access each element using get() method.
Following is an working example. See it working here:
public static void main (String[] args) throws java.lang.Exception
{
try(Scanner stdin = new Scanner(System.in))
{
int numberofsquares=1;
int prgrm=0;
int v=1;
List<List<String>> square = new ArrayList<>();
while(prgrm==0)
{
System.out.println("Enter another square? (y/n)");
if (stdin.next().startsWith("y"))
{
for(int i=0; i<3; i++)
{
square.add(new ArrayList<String>());
//Get last element's index
int lastIndex = square.size()-1;
//Get last element and add a String
square.get(lastIndex).add((i+1) +","+v+","+stdin.next());
v++;
}
}
else
{
prgrm++;
}
}
if (prgrm==1)
{
System.out.println("Finish");
}
System.out.println("Lists are: " + square);
}
}
Use nested lists, eg:
List<List<String>> squares = new ArrayList<>();
Related
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");
}
This question already has answers here:
Find an array inside another larger array
(15 answers)
Closed 4 years ago.
I defined an array which contains random numbers.I get some numbers from the user and put them in other array.I want to check whether first array contains the second array in order.My code is not enough to check order.It is just checking contains or not.
EX:
arr1=[45, 21,1,19 ,8,90,21,2] ,arr2=[21,1,19]
result=TRUE
arr1=[45,21,1,19,8,90,21,2] ,arr2=[21,19] result=FALSE
public class Main {
private static int[] array1;
public static int[] list() {
array1 = new int[10];
for(int i=0;i<array1.length;i++)
{
array1[i] = randomFill();
}
return array1;
}
public static void print()
{
for(int n: array1)
{
System.out.println(n+" ");
}
}
public static int randomFill()
{
Random rand = new Random();
int randomNum = rand.nextInt(90)+10; //to generate two digits number which is between 10-99 to the array
return randomNum;
}
public static void main(String args[])
{
list();
print();
Scanner s=new Scanner(System.in);
System.out.println("How many numbers will you add? ");
int n=s.nextInt();
int array2[]=new int[n];
System.out.println("Enter the numbers:");
for(int i=0;i<n;i++){//for reading array
array2[i]=s.nextInt();
}
for(int i: array2){ //for printing array
System.out.println(i);
}
int result=0;
for(int i=0;i<array1.length;i++)
{
for(int j=0;j<array2.length;j++)
{
if(array1[i]==array2[j])
{
result=result+1;
}
}
}
if(result==n)
{
System.out.println("TRUE");
}
else
{
System.out.println("false");
}
}
}
Here is the hard way without any helper
Integer i,j,k;
Boolean found=false;
for(i=0;i<arr1.length;i++) {
// we look for the index of the first element of the second array in the original one
if(arr2[0] == arr1[i] ) {
found=true;
// after that we iterate in both arrays simultaneously
for(j=1, k=i+1; j<arr2.length; j++,k++) {
// if we complete the iteration of the original array
// or if we find any two elements not equal we break
// we set then the boolean variable to false
if( k>=arr1.length || arr2[j] != arr1[k] ) {
found=false;
break;
}
}
if(found) break;
}
}
System.out.println(found);
I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}
I have created an array of type Savings which contains a String (Name) and a double (Account Number). I want to search using an Account Number and see if it exist and then return all the elements (Name + Account Number) and the Index of the Array that contain these elements. I tried this but it does not work.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Savings[] ArrayOfSavings = new Savings[5];
System.out.print("Enter Account Number: ");
Scanner scan = new Scanner(System.in);
double Ms = scan.nextDouble();
//Loop until the length of the array
for(int index = 0; index<= ArrayOfSavings.length;index++){
if(ArrayOfSavings[index].equals(Ms)){
//Print the index of the string on an array
System.out.println("Found on index "+index);
}
}
ArrayOfSavings[0] = new Savings("Giorgos",87654321);
ArrayOfSavings[1] = new Savings("Panos",33667850);
}
}
/Savings Class/
public class Savings extends Generic {
public Savings(String FN, double AN) {
super(FN, AN);
}
#Override
public String toString(){
return String.format("Customer: %s \n Acount Number: %.1f,
getFirstName(),getAccNumber();
}
}
You could do something like this, where you return -1 if it doesn't exist, or the index if you've found it. Just have to make sure you check for this case.
public static int findSavingsIfExists(double accountNumber, Savings[] allSavings) {
for(int i = 0; i < allSavings.length(); i++) {
if(allSavings[i].accountNumber == accountNumber) {
return i;
}
}
return -1;
}
and use it like so
int index = findSavingsIfExists(..., ArrayOfSavings);
if(index != -1) {
Savings foundSavings = ArrayOfSavings[index];
} else {
//Not found
}
Try to use somethig like this:
double Ms = scan.nextDouble();
int index = 0;
for (int i = 0; i < ArrayOfSavings.length; i++) {
if (ArrayOfSavings[i].getAccountNumber == Ms ) {
index = i;
break;
}
}
System.out.println(index);
I'm trying to create a lotto, where you have to read in a data file and match the numbers read in to winning numbers given through the console, my problem is that in the for loop where i read in the players numbers, it reads in fine, i even did a
system.out.print(ticketList.get(i).getNumbers()[j]+" ");
that checked if the numbers were correct, which they were, but when i did the same line of code outside the for loop where i add the instance of a ticket to the arraylist
ticketList.add(new Ticket(Players[i],ticketnumbers));`
It all gets over taken by the last instance ticket that was created, but the wierd part is, its only the player numbers that get over taken, not the player names, so thats what really threw me off, I've been sitting on it for a while trying to find stuff, but I've come up empty so far, any help would be appreciated!
I wanna say that the rest of the code works, because if i put the winning numbers as the last persons numbers he wins the lotto lol. I just know that when i try to match the number arrays it only uses the last persons numbers instead of everyone's individual numbers, so thats why that piece of code does not work.
public class Lottery{
static ArrayList<Ticket> ticketList = new ArrayList();
public static void scanFile() throws FileNotFoundException
{
String fileName;
int[] WinningNumbers = new int[6];
Scanner scan = new Scanner(System.in);
System.out.println("enter a string");
fileName = scan.nextLine();
System.out.println("Enter the winning Lottery Numbers");
for(int i =0; i<WinningNumbers.length;i++)
{
WinningNumbers[i] = scan.nextInt();
}
scan.close();
int NumberofTickets;
File file = new File(fileName);
Scanner scanInput = new Scanner(file);
NumberofTickets = scanInput.nextInt();
scanInput.nextLine();
String[] PlayersName = new String[NumberofTickets];
int[] ticketnumbers = new int[6];
for(int i=0; i < NumberofTickets;i++)
{
scanInput.nextLine();
PlayersName[i] = scanInput.nextLine();
scanInput.nextLine();
for(int j = 0 ; j<6;j++)
{
ticketnumbers[j] = scanInput.nextInt();
}
if(i != NumberofTickets-1)
scanInput.nextLine();
ticketList.add(new Ticket(PlayersName[i],ticketnumbers));
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
for(int i=0; i < NumberofTickets;i++)
{
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
checkTickets(WinningNumbers,NumberofTickets);
scanInput.close();
}
public static void checkTickets(int[] winningNumbers, int NumberofTickets)
{
int[] winnersMatchedNumbers = new int[6];
for(int i =0; i<NumberofTickets; i++)
{
int counter = 0;
if(winningNumbers[j] == ticketList.get(i).getNumbers()[j])
{
counter = counter+1;
}
}
winnersMatchedNumbers[i] = counter;
}
Winners(winnersMatchedNumbers,NumberofTickets);
}
public static void Winners(int[] matchedNumbers, int NumberofTickets)
{
for(int i = 0; i<NumberofTickets;i++)
{
System.out.println(ticketList.get(i).getTicketName()+ " matched "+ matchedNumbers[i]+" and won "+ ticketList.get(i).getWinnings(matchedNumbers[i]));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
scanFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the other class i am using is here
public class Ticket
{
private String ticketName;
private int[] personNumber = new int[6];
public Ticket(String Name,int[] ticketNumbers)
{
ticketName = Name;
personNumber = ticketNumbers;
}
public String getTicketName()
{
return ticketName;
}
public int[] getNumbers()
{
return personNumber;
}
public int getWinnings(int count)
{
int winningsAmount;
switch(count)
{
case 3: winningsAmount = 10;
break;
case 4: winningsAmount = 100;
break;
case 5: winningsAmount = 10000;
break;
case 6: winningsAmount = 1000000;
break;
default: winningsAmount = 0;
break;
}
return winningsAmount;
}
}