Strange issue with an array - java

So I'm in the middle of working on a class called planner [no main in it as it's a separate class], but I'm having an issue with declaring an array with eclipse. You will need to enter it in eclipse to see what it is because I have no idea what it means by 'Syntax error on token ";", , expected'.
Here is the code:
import java.util.Scanner;
public class Planner {
private int maxEvents = 1000;
private int numEvents = 0;
private int choice;
int[] anArray;
anArray = new int [1000];
public void Planner() {
Scanner scan = new Scanner (System.in);
System.out.print("Press 1 to add an event. 2 to display events for the day. 3 to display events for the week. 4 to quit: ");
choice = scan.nextInt();
if (choice == 1){addEvent();}
if (choice == 2){displayOneDate();}
if (choice == 3){displayOneWeek();}
if (choice == 4){System.out.println("Have a good day.");}
else {Planner();}
}
public void addEvent() {
Event newEvent = new Event();
if (numEvents == maxEvents){System.out.println("Error: No more room.");}
else {
for (int i=0; anArray.length > i; i++) {
numEvents++;
newEvent.getEventFromUser();
}
}
}
public void displayOneDate() {
System.out.println("Event one: " + anArray[0]);
}
public void displayOneWeek() {
}
}

When you declare
int[] anArray;
anArray = new int [1000];
it should be
int[] anArray = new int [1000];

You cannot have executable code in class directly. You should have it either in method or constructor.
Otherwise if you want initialize the array you have to write like this int[] anArray = new int [1000];

Related

Java array values gets overwritten

I am new to Java and this is a very basic question.
However I struggle to find a solution, so hopefully someone could give me some pointers.
I am trying to fill values into an array "addedPlayer".
However, every time I run the AddPlayer() method it is initialiezed to zero again.
How can I structure this in a better way?
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public void AddPlayer() {
int[] addedPlayer;
addedPlayer = new int[500];
System.out.println(" *** Add new player *** ");
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
System.out.println(addedPlayer[0]);
for (int j = 0; j < addedPlayer.length; j++) {
if (addedPlayer[j] != 0) {
} else {
addedPlayer[j] = p.GetAge();
System.out.println(addedPlayer[j]);
System.out.println(j);
break;
}
}
}
public void EditPlayer() {
//empty
}
public void ListPlayer() {
//empty
}
#Override
public void run(String... args) throws Exception {
while (true) {
System.out.println(" *** MENY *** ");
System.out.println(" 1. Add player ");
System.out.println(" 2. Edit player ");//ÖKurs
System.out.println(" 3. List player ");
System.out.println(" 100. Exit ");
System.out.println("Ange val");
int sel = Integer.parseInt(System.console().readLine());
if (sel == 100) break;
if (sel == 1) AddPlayer();
if (sel == 2) EditPlayer();
if (sel == 3) AddPlayer();
}
}
}
Each time you run AddPlayer(), it creates a new player from scratch. If you want to keep your modifications to a bare minimum, you must put it outside of the method and make it a property for your class like List<int[]> addedPlayers = new ArrayList<int[]>(); and you can add this line AddPlayer to add it in a list addedPlayers.add(addedPlayer). Otherwise, if you want a more cleaner code, you should add more classes than only one main class. To improve your code, you can see #g.momo's answer.
int[] addedPlayer; addedPlayer = new int[500];
It gets overridden because you are creating an new local var addedPlayer, and then setting all values to 0 (addedPlayer = new int[500];) I'm assuming you would want addedPlayer to be global, so don't define it locally and set it to 0.
Also, should addedPlayer be a player[] or just a player rather than an int[]? Plus, you didn't close the function in the code you gave us, so is there more missing or did you just not close it?
Your code and your expectations are completely differents.
Read this and tell us if you understand. It is the way I would have written if I were you . But it is NOT TESTED:
public class AddPlayer { // you create a class
player[] addedPlayer; // array of players
int index;
public AddPlayer() { // constructor of the class
addedPlayer = new player[500]; // max 500 players
index = 0;
}
public void addPlayer(player p) {
if(index < 500) {
addedPlayer[index] = p; // add at index,
index = index + 1; // then increment index for the next added player
}
}
public static void main(String... args) {
AddPlayer addPlayers = new AddPlayer();
int i = 0;
while(i < 5) { // will run 5 times, so only 5 players will be added. Change to stop when you will need
// here your read console inputs
System.out.println(" *** Add new player *** "+ (i+1));
System.out.println("Name:");
String name = System.console().readLine();
System.out.println("Age:");
int age = Integer.parseInt(System.console().readLine());
System.out.println("JNUM:");
int jnum = Integer.parseInt(System.console().readLine());
// initialize the player
player p = new player();
p.SetAge(age);
p.SetName(name);
p.SetJnum(jnum);
addPlayers.addPlayer(p); // add in the array
i++;
}
}
}

How to use one scanner for both integers and text?

I need to make a program that allows me to ask the user for a few numbers and keep doing that until the user enters a 'q' but i cant seem the get the hasNextInt to work as i thought it worked. I am very new to Java and doing the ground course atm.
Here is what i have done so far
public class Matte
{
public static void main (String[] args)
{
int r1 = 0;
int h1 = 0;
int r2 = 0;
int h2 = 0;
int level = 1;
String choice = new String();
Scanner values = new Scanner(System.in);
values.useDelimiter("\\s");
if (level == 1)
{
if(!values.hasNextInt())
r1 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
h1 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
r2 = values.nextInt();
else choice = values.nextLine();
if(!values.hasNextInt())
h2 = values.nextInt();
else choice = values.nextLine();
}
}
}
I want to save what ever text is typed in the scanner in the "choice" variable
How do i do it??
I didn't really understand your problem, but here is a solution for your problem, adding these integers to an ArrayList and stoping the program when the user types 'q'. Hope it helps you. Cheers!
public class Matte
{
public static void main (String[] args)
{
ArrayList<Integer> numbers = new ArrayList();
int level = 1;
String choice;
Scanner values = new Scanner(System.in);
values.useDelimiter("\\s");
if (level == 1)
{
while(true){
choice = values.nextLine();
if(choice.equals("q"))
break;
else
numbers.add(Integer.parseInt(choice));
}
}
}
}

How can I pass an Array from one class to another?

I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
}
}
import java.util.Scanner;
public class takeAGuess {
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
public class board {
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
}
I already tried these lines:
new[] board = board.Createboard();
int board[] = board.Createboard();
{
int board = new board();
board = createBoard();
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes therefore I create lots of them.
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
where is playboard defined?
And... so much classes! Use methods in the Main class instead, it'll make your job lighter.

JAVA error cannot find a symbol

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

Using standard input in java, how to input an entire array of integers? [duplicate]

This question already has answers here:
How to read array of integers from the standard input in Java?
(2 answers)
Closed 8 years ago.
So my code looks like this so far:
public class PancakeSort {
public static int flip(int n) {
int temp = 0;
for (int i = 0; i < (n+1) / 2; ++i) {
int[] pancakes = new int[n];
temp = pancakes[i];
pancakes[i] = pancakes[n-i];
pancakes[n-i] = temp;
}
return temp;
}
public static void sort (int[] pancakes) {
for (int i=0; i<pancakes.length; i++){
if (pancakes[i] > pancakes[i+1]){
flip(i+1);
}
}
System.out.println(pancakes);
}
public static void main(String[] args) {
}
}
But how I input a whole array of integers using standard input (StdIn.readLine())? I understand that the code might not be correct and I'm working on figuring that out,and I'm also aware that this question has been asked before in this site, but not specifically using the standard library and that is where I'm stuck.
You can send integer array as input
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(new int[] { 100, 50, 89, 2, 5, 150 });
or Use scanner class as
int arr[] = new int[10];
Scanner sc = new Scanner(System.in);
int i = 0;
while (sc.hasNextInt()) {
arr[i] = sc.nextInt();
i = i + 1;
}
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(arr);
But in last case you must not increased the size of array.Otherwise it will give arrayIndexOutOfBoundException
I believe you may be referencing StdIn such as a class like this one?
http://introcs.cs.princeton.edu/java/stdlib/StdIn.java.html
If so, then to get an int from the console you just call StdIn.readInt. An example of how you could approach this is:
public static void main(String[] args)
{
System.out.println("Enter number of pancakes, or enter 0 to quit");
int[] pancakeArray = new int[0];
while (true)
{
try
{
int entry = StdIn.readInt();
if (entry == 0)
{
break;
}
int[] expandedArray = new int[pancakeArray.length + 1];
System.arraycopy(pancakeArray, 0, expandedArray, 0, pancakeArray.length);
expandedArray[pancakeArray.length] = entry;
pancakeArray = expandedArray;
}
catch (Exception e)
{
System.out.println("Invalid entry detected, closing input");
break;
}
}
System.out.println("Pancake array length: " + pancakeArray.length);
sort(pancakeArray);
System.out.println("Final pancake array in order:");
for (int entry : pancakeArray)
{
System.out.println("Pancake value: " + entry);
}
}
This would read int after int until they entered 0 or an invalid value, then it would call your sort routine from there. There are issues in your sort routine but you said you wanted to look at that, so I will let you figure that part out.

Categories