Java int error cant be int[] - java

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.

Related

random Strings in ArrayList

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.

When compiling program I get the error 'void' type not allowed here

I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);

2 user inputs with condition and use in another method

I'm doing a school project which asks me to do the following in separate methods:
start a main method and present the program
ask for user to input 2 numbers (conditions a>b and both positive & if it's wrong to ask 3 times or finish program by letting user it's over)
if conditions are ok, it should print first 2 consecutive number starting from a number, and last 2 consecutive numbers from b number.
I am dealing with several problems but biggest of them is that I can't use global variables so I should pass the numbers from a method to the other.
How can I do that?
The code I tried is
import java.util.Scanner; //Importar scanner
public class Eac4_001 {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Eac4_001 programa = new Eac4_001();
programa.inicio();
}
public void inicio() {
presentarPrograma();
pedirNumeros();
mostrarResultado();
}
public void presentarPrograma() {
System.out.println("El programa pedirá dos números positivos.\n"
+ "El primero tiene que ser más pequeño que el segundo.\n"
+ "Luego enseñará los primeros y ultimos dos númberos del"
+ "rango conseguido.\n");
}
public void pedirNumeros() {
int intentos = 3;
boolean ok = false;
int a = 0, b = -1;
while (a > b && !ok) {
System.out.print("Introduce un primer número: ");
a = scanner.nextInt();
System.out.print("Introduce un segundo número: ");
b = scanner.nextInt();
intentos = intentos - 1;
if (intentos < 0) {
ok = false;
}
System.out.println("Error, vuelve a introducir los números!");
}
}
public void mostrarResultado() {
}
}
I have made a few changes in your code.
import java.util.Scanner; //Importar scanner
public class Eac4_001 {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Eac4_001 programa = new Eac4_001();
programa.inicio();
}
public void inicio() {
presentarPrograma();
pedirNumeros();
}
public void presentarPrograma() {
System.out.println("El programa pedirá dos números positivos.\n"
+ "El primero tiene que ser más pequeño que el segundo.\n"
+ "Luego enseñará los primeros y ultimos dos númberos del"
+ "rango conseguido.\n");
}
public void pedirNumeros() {
int retry = 0;
int input1, input2;
boolean ok = false;
do {
System.out.print("Introduce un primer número: ");
input1 = scanner.nextInt();
System.out.print("Introduce un segundo número: ");
input2 = scanner.nextInt();
if (input1 > 0 && input2 > 0) {
ok = true;
//call your method from here.
mostrarResultado(input1, input2);
} else {
System.out.print("Invalid Input. Try again.");
if (retry < 3) {
retry++;
} else {
break;
}
}
} while (!ok);
}
public void mostrarResultado(int input1, int input2) {
//Do whatever you want to do, here with these variables
}
}
To send numbers from one method to the other, you can pass them as arguments in to another function.
Example
public void method1(int a, int b){
//code
}
Above method receives two integer values as arguments.
Link to learn about basics of methods in JAVA
Another way to pass numbers from one method to another is by returning the number from the method and then calling that method from another method in which you want to pass the number.
If you only want to pass one number to another method, you can simply return it.
Example
public int method2(){
int a = 20;
return a;
}
or if you want to pass more than one numbers, you can store them in an array and then return that array
Example
public int[] method3( )
{
int[] x;
x = new int[3]; // Create an array of 3 elements
x[0] = 2;
x[1] = 3;
x[2] = 4;
return( x );
}
In Java, a method can only ever return one value. If Java didn't have this restriction, then you could write:
greeting();
int (a, b) = readNumbers();
output(a, b);
But since the second line is not valid Java, you have to do something else. The following comes very close:
greeting();
int[] numbers = readNumbers();
output(numbers[0], numbers[1]);
At the end of the readNumbers method, you can write:
return new int[] { first, second };
Note that the array is only used for the return value of the second method. In particular, it is not passed further to the third method. Doing that would be unnecessary because Java allows multiple parameters.
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public Test() {
}
public static void main(String [] args){
int [] myNumbers = new int[2];
present();
input(myNumbers);
presentResult(myNumbers);
}
public static void present(){
System.out.println("This is my presentation");
}
public static void input(int [] n){
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 2;i++){
n[i] = scan.nextInt();
while(n[i] < 0){
System.out.println("Your number has to be higher then 0");
n[i] = scan.nextInt();
}
if(n[1] < n[0] && i == 1){
System.out.println("The 2:nd number needs to be greater the the first one");
n[i] = scan.nextInt();
}
}
}
public static void presentResult(int [] n){
Arrays.sort(n);
System.out.println(Arrays.toString(n));
}
}
So this works.

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

No suitable method found? Please assist me in completing this?

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.

Categories

Resources