I have the following code:
public class classroom{
public static void main(Integer[] args) {
int teachers = args[0];
int students = args[1];
int desks = args[2];
int computers = args[3];
double ratio = students/desks;
if (teachers == 1) {
if (computers >= students) {
if (ratio <= 6) {
System.out.println("this classroom is vald");
}
}
}
else {
System.out.println("this classroom is not valid");
}
}
}
I run the code as classroom.main(1, 2, 3, 4), and java returns the following error: 'identifier expected'. Any idea how I should solve this problem?
You should solve this problem call method as:
Classroom.main(new Integer[]{1, 2, 3, 4});
I think you need ... operator, Calling Classroom.main(1, 2, 3, 4) will require you to change the method Argument with three dot operator. By using Three dot operator ... You can pass integer arguments without explicitly creating array.
public class ClassRoom {
public static void main(String[] args) {
ClassRoom.main(1, 2, 3, 4);
}
private static void main(Integer... args) {
for (Integer i : args) {
System.out.println("Argument [ " + i + " ] = " + args[i-1]);
}
}
}
You should call the function by classroom.main(new Integer[] { 1, 2, 3, 4 }), instead of classroom.main(1, 2, 3, 4).
Because the function declares as classroom.main(Integer[] args), but not classroom.main(int a, int b, int c, int d).
Another advice: Java class name should use Camel Case for the Java naming convention.
Related
The version of java: SDK 1.8.0_151
IDE: IDEA IntelliJ
import java.awt.Queue;
import java.util.LinkedList;
public class SimpleMovingAverage {
private final Queue<Double> window = new LinkedList<Double>();
private final int period;
private double sum;
public SimpleMovingAverage(int period) {
assert period > 0 : "Period must be a positive integer";
this.period = period;
}
public void newNum(double num) {
sum += num;
window.add(num);
if (window.size() > period) {
sum -= window.remove();
}
}
public double getAvg() {
if (window.isEmpty()) {return 0.0;} // technically the average is undefined
return sum / window.size();
}
public static void main(String[] args) {
double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};
int[] windowSizes = {3, 5};
for (int windSize : windowSizes) {
SimpleMovingAverage ma = new SimpleMovingAverage(windSize);
for (double x : testData) {
ma.newNum(x);
System.out.println("Next number = " + x + ", SMA = " + ma.getAvg());
}
System.out.println();
}
}
}
The code above is coming from https://rosettacode.org/wiki/Averages/Simple_moving_average#Java
When I create a Class, called SimpleMovingAverage and copy the code from the above website, an error is reported.
'java.awt.Queue' is not public in 'java.awt'. Cannot be accessed from outside package
How to solve it?
You need java.util.Queue not java.awt.Queue, which can hold whatever you want
The java.awt package is about UI, graphics and images: Documentation, and the java.awt.Queue is here to hold java.awt.Event elements
For Improvement ONLY : for the implementation of a Circular FIFO, here some infos
Is there a fixed sized queue which removes excessive elements?
Basic implem of a CircularQueue
Which could give something like
public void newNum(double num) {
window.add(num);
}
I have a method that accepts any number of INTEGER parameters:
pages(int,int...)
This method is to select some pages of PDF file.
Book Pages stored as a string type like this:
String pages = "1,2,3,6,9";
I want to make this string as the parameter of the method to look like:
pages(1,2,3,6,9);
This can be easily done with streams:
Stream
.of(commaSeparated.split(","))
.mapToInt(Integer::parseInt)
.toArray();
You can combine this with varargs to get what you want:
public static void main (String[] args) {
String commaSeparated = "0,1,2,3,4,5,6,7,8,9";
int[] arguments =
Stream
.of(commaSeparated.split(","))
.mapToInt(Integer::parseInt)
.toArray();
pages(arguments);
}
public static void pages(int... numbers) {
System.out.println("numbers: " + Arrays.toString(numbers));
}
Output will be:
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: of course varargs isn't needed in this specific case, it's useful only if you plan to call the same method with a variable number of int arguments, otherwise you can just change its signature to pages(int[] numbers).
Do this :
public class Test {
public static void main(String..args) {
String pages = "1,2,3,6,9";
String[] pagesArr = pages.split(",");
pages(pagesArr);
}
static void pages(String... pagesArr) {
int[] array = Arrays.asList(pagesArr).stream().mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
I am new to this programming world. I tried to print length of the array without using predefined functions.
But when i run my code i am getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
can someone please help me to find out the bug
Here is my code.
public class Arraylen {
public static void main(String[] args) {
int[] ary = {1, 3, 4, 5, 68, 9};
int len;
for(len = 1; ary[len] != '\0'; len++) {
System.out.println(len);
}
}
}
What is wrong with using ary.length? .length is a property and not a function. You would not be coding ary.length(), let alone that "function" doesn't even exist.
public class StackOverflow {
public static void main(String args[]) {
int[] ary = {1, 3, 4, 5, 68, 9};
System.out.println(ary.length);
}
}
Result:
6
Just use an enhanced for loop:
public class Arraylen
{
public static void main(String[] args)
{
int[] ary = {1,3,4,5,68,9};
int len = 0;
for(int number : ary)
{
len++;
}
System.out.println(len);
}
}
This iterates over every item in the array, without you having to worry that the index will go over the array size.
You could also use a while loop with a try-catch block to find the length.
Something like this:
boolean lengthFound = false;
int length = 0;
while (!lengthFound) {
try {
// This line throws an Exception when length is equal to the length of the array
int notImportant = array[length] + 2;
length++;
}
// This prevents the exception from breaking anything and gets you out of the
// loop
catch (ArrayOutOfBoundsException ex) {
lengthFound = true;
}
}
// At this point array.length == length
import java.util.*;
public class ArrayList5 {
static int max(ArrayList list) { // to be completed
if (list.size() == 0) {
return 0;
}
else
{
int first = (Integer) list.get(0);
list.remove(0);
if (first > max(new ArrayList(list)))
{
return first;
}
else
{
return max(list);
}
}
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
Collections.addAll(list, 4, 5, 3, 2, 3, 1, 3);
// int t=Console.readInt("Enter Target:");
int res1 = max(new ArrayList(list));
System.out.println("max=" + res1);
}
}
I don't understand why the max(new ArrayList(list))) part is required. Why does it have to create a new one and why can't it continue to work with the one list?
Also why doesn't it get caught in a loop (it's recursion so it will keep sending up a new list so I don't understand why 'first' isn't going to be 4 every time)?
Actually, there is a lot of superfluous code that is not required and make the code cumbersome/more difficult to read/understand.
You can simplify the code a lot and get rid of any reference to ArrayList which are not really necessary and by using proper generic at the right places, make the code actually readable.
You don't need to cast or create list all over the place.
public class ArrayList5 {
static int max(final List<Integer> list) {
if(list.isEmpty()) return 0;
final int head = list.get(0);
final List<Integer> tail = list.subList(1, list.size());
return (head > max(tail)? head:max(tail));
}
public static void main(final String... args) {
final int res1 = max(Arrays.asList(4, 5, 3, 2, 3, 1, 3));
System.out.printf("max=%d", res1);
}
}
You should try this:
static int max(ArrayList<Integer> list) {...}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
Collections.addAll(list, 4, 5, 3, 2, 3, 1, 3);
// int t=Console.readInt("Enter Target:");
int res1 = max(new ArrayList(list));
System.out.println("max=" + res1);
}
The compiler is probably throws a warning because you don't declare the type of the ArrayList.
How to count repeated elements in given array? Please give me any suggestion as an alternative for this problem.
public static void main(String[] args)
{
// TODO Auto-generated method stub
int a[]={1,2,3,1,2,4,4,4,5};
int c=0;
for(int i=0;i!='\0';i++)
{
c=1;
for(int k=i+1;k<9;k++)
{
if(a[i]==a[k] && a[i]!='\0')
{
c++;
// a[k]='\0';
}
}
if(a[i]!='\0')
{
System.out.println("value is"+a[i]+"repeated in"+c);
System.out.println("\n");
}
}
}
Here's another simple approach that does not require a separate data structure:
Sort the array using Arrays static method
Now you can iterate over the array knowing all duplicates will be grouped together. Shouldn't be hard to figure out....
Pilfering my code from another answer:
public static void main(String[] args) throws Exception {
int[] a = {1, 2, 3, 1, 2, 4, 4, 4, 5};
final Counter<Integer> counter = new Counter<>();
IntStream.of(a).forEach(counter::add);
IntStream.rangeClosed(1, 5).forEach(i -> {
System.out.printf("%s has a count of %s%n", i, counter.count(i));
});
}
public static class Counter<T> {
final Map<T, Integer> counts = new HashMap<>();
public void add(T t) {
counts.merge(t, 1, Integer::sum);
}
public int count(T t) {
return counts.getOrDefault(t, 0);
}
}
Output:
1 has a count of 2
2 has a count of 2
3 has a count of 1
4 has a count of 3
5 has a count of 1