Java for-loop is not executed - java

The first for-loop you see does not execute and I'm not sure why. It is completely ignored, I tried it in a separate method and I tried it in the main method but something seems to be ignoring but I'm not sure how to get it to run, it simply goes to the next method run in the main method.
package math;
import java.util.Scanner;
public class mathAverageValue {
static int numOfVals;
static double total;
static double average;
static double[] arr = new double[numOfVals];
static String boole;
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
public static void process() {
for (int i=0; i < arr.length; i++) {
total = total + arr[i];
}
average = total / arr.length;
}
public static void output() {
System.out.println("Your average is : " + average);
System.out.println("Would you like to average again? Y or N : ");
Scanner i = new Scanner(System.in);
boole = i.next();
if ("Y".equals(boole)) {
input();
output();
}
}
public static void main(String[] args) {
input();
output();
}
}

Assign some value to static int numOfVals. Java by default assign 0 to it. Hence your for loop will never run. Also modify your array declaration like below:-
static double arr = new double[numOfVals];

The problem is that you have assigned a value to numOfVals and then created the array in the wrong order.
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
arr = new double[numOfVals]; // <-- PUT THIS HERE
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}

It is ignored because it is a zero length array:
static int numOfVals; // This implicitly equals 0.
static double total;
static double average;
static double[] arr = new double[numOfVals]; // so this has no elements.
hence
for(int i=0; i<arr.length; i++){ //arr.length is 0
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
doesn't iterate

According to java primitive data types initialization, all types have a default value. In your case, static int numOfVals will be assigned with 0. This is the reason why the for loop is ignored. see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Related

How to call multiple arrays in a void method?

I am stuck on how to call my method.
I get a cannot find symbols (playerName,battingArray) error message.
-Am I not calling it correctly?
-Is the method set up to populate the arrays properly?
I am not even sure if this is the best way to go about doing this.
ANY HELP IS SO GREATLY APPRECIATED!!
//Import util to accept input
import java.util.Scanner;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//Assign number of players to variable and call method readNumPlayers
int numPlayers = readNumPlayers();
System.out.println(numPlayers);
//Call readData method
readData(playerName, numPlayers, battingArray);
}//end main
//readNumPlayers method
public static int readNumPlayers() {
System.out.println("Number of players: ");
int numPlayers = input.nextInt();
if (numPlayers <=0) {
System.out.println(" Error- Try again ");
System.out.println("Number of players: ");
numPlayers = input.nextInt();
}//end catch to ensure entry is positive integer
return numPlayers; //return
}//end readNumPlayers
//readData method
public static void readData(String[] playerName, int numPlayers,
double[] battingArray) {
playerName = new String[numPlayers];
System.out.println("Enter player's last name: ");
for (int i = 0; i < playerName.length; i++) {
playerName[i] = input.next();
} //end for loop
battingArray = new double[numPlayers];
System.out.println("Enter player's batting average: ");
for (int i = 0; i < battingArray.length; i++) {
battingArray[i] = input.nextDouble();
}// end for loop
}//end readData
}
When you pass the arrays as parameters the caller of readData is supplying references to the arrays to fill in, and, while you can affect the contents of the array referenced you can't change the reference itself — so you should not allocate arrays in your method - for example, your line:
battingArray = new double[numPlayers];
When you allocate a new array and fill that in, the caller has no access to that array, and you have not put anything in the array that the caller passed (and does have access to)
Just use the double[] battingArray parameter that the caller passed in.
Here are two versions of a very simple example; in the first the readData method allocates it's own array and fills it in. You'll see that when main prints the array content you get null because the array filled by readData is not the same array that was passed.
In the second, readData just puts values into the array that the caller passed.
First:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// allocating a new array
String[] playerNames2 = new String[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// putting the value into the newly allocated array
playerNames2[i] = line.trim();
}
System.out.println("playerNames2[0] in readData: " + playerNames2[0]);
}
}
Second:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// no array allocated this time
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// put the value into the array that was passed
playerNames[i] = line.trim();
}
System.out.println("playerNames[0] in readData: " + playerNames[0]);
}
}
Since the caller is telling you how big the arrays are (numPlayers parameter), let's say "10", if the caller's arrays aren't actually big enough (say they did new String[5]) it's possible that you get an ArrayIndexOutOfBoundsException, so readData would probably want to catch that and return without finishing the loop.
(I've created a Java repl where you can see version 2)

How to input two numbers in Main using Scanner and make it work with a method (Ascending order java)?

I'm trying to make this program that will print out numbers in ascending order between two input numbers. I made it work as a method and I can call the method in Main, but what I really want to do is to input the two numbers in Main and not in the method.
So something like this:
System.out.println(”Two numbers in ascending order”);
(input two numbers in console)
And then after this, call the method that will print in ascending order between the chosen numbers of Main.
I’m new to this and i’ve tried several things, but I can’t seem to figure out what to do. Would appreciate som help.
This is how the code looks now.
import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
// calling method
int ascending1 = ascending();
}
public static int ascending() {
int min;
int max;
int total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
min = sc.nextInt();
max = sc.nextInt();
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
Pass in the two inputs as parameters to your method, something like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
System.out.println(ascending1);
}
And now :
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
Notice that now the definition of ascending() takes in two parameters of type int. The values are passed from the main method to the method.
You can input the numbers in the main method and then pass them to another method:
public class AscendingOrder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Two numbers in ascending order");
int min = sc.nextInt();
int max = sc.nextInt();
int ascending1 = ascending(min, max);
}
public static int ascending(int min, int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
You can read the command line arguments or place the scanner in main function and pass the arguments
import java.util.Scanner;
public class AscendingOrder {
public static void main(String[] args) {
System.out.println("Entered first number is: "+args[0]);
System.out.println("Entered Secomd number is: "+args[1]);
int ascending1 = ascending(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static int ascending(int min,int max) {
int total = 0;
for (int i = min; i < max + 1; i++) {
System.out.print(i + " ");
total += i;
}
return total;
}
}
You can get the numbers in main method and sort them in the main method itself. Java 8 makes it so easy with streams.
public static void main( String[] args ) throws Exception {
Framework.startup( );
Scanner sc = new Scanner( System.in );
System.out.println( "Two numbers in ascending order" );
int num1= sc.nextInt( );
int num2= sc.nextInt( );
Arrays.asList( num1, num2).stream( ).sorted( ).forEach( System.out::println );
}

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

Trying to print the frequency of integers in an array

I'm trying to print out the frequency of each integer in an array
import java.util.*;
public class NumFrequency {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of numbers your going to input, up to 50");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the "+ num + " numbers now.");
for (int i=0 ; i<array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("array created");
printArray(array);
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i=0; i<n; i++) {
System.out.print(arr[i]+" ");
}
}
private static int[] intFreqArray = new int[51];
public static void FreqOfInt(int[] array, int num) {
for (int eachInt : array) {
intFreqArray[eachInt]++;
}
for (int m = 0; m<intFreqArray.length; m++) {
if (intFreqArray[m] > 1) {
System.out.println(m+ " occurs " + intFreqArray[m] + " times.");
}
}
}
}
It'll print out the array created by the user but nothing after that I'm lost as to why it wont print out the last part.
You need to call FreqOfInt before you print.
Note that we normally use lower case letters for the names of Java methods.
In main, the last method call is to printArray, but you never call FreqOfInt. That's why that output doesn't show up.
Call it after calling printArray.

method in class cannot be applied to given types

I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)
When I compile the program I get the error:
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();
required: int[]
found:generateNumbers();
reason: actual and formal argument lists differ in length
I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [99];
//calls the generateNumbers method
generateNumbers();
//calls the displayCounts method
displayCounts();
}
//*****************************************************************
private static int generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
return randomNumber;
}
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int[] frequency = new int[10];
for(int i = 0, size = numbers.length; i < size; i++ ){
System.out.println((i) + " counts = " + frequency[i]);
}
}//end of displayCounts
}//end of class
generateNumbers() expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error
The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.
To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.
I think you want something like this. The formatting is off, but it should give the essential information you want.
import java.util.Scanner;
public class BookstoreCredit
{
public static void computeDiscount(String name, double gpa)
{
double credits;
credits = gpa * 10;
System.out.println(name + " your GPA is " +
gpa + " so your credit is $" + credits);
}
public static void main (String args[])
{
String studentName;
double gradeAverage;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter Student name: ");
studentName = inputDevice.nextLine();
System.out.println("Enter student GPA: ");
gradeAverage = inputDevice.nextDouble();
computeDiscount(studentName, gradeAverage);
}
}
pass the array as a parameter when call the function, like
(generateNumbers(parameter),displayCounts(parameter))
If you get this error with Dagger Android dependency injection, first just try and clean and rebuild project. If that doesn't work, maybe delete the project .gradle cache. Sometimes Dagger just fails to generate the needed factory classes on changes.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [100];
//calls the generateNumbers method
generateNumbers(numbers); //passing the empty array
//calls the displayCounts method
displayCounts(numbers); //passing the array filled with random numbers
}
//*****************************************************************
private static void generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
} // here the function doesn't need to return.Since array is non primitive data type the changes done in the function automatically gets save in original array.
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int count;
for(int i = 0, size = 10; i < size; i++ ){
count=0;
for(int j = 0; j < numbers.length ; j++ ){
if(i == numbers[j])
count++; //counts each occurence of digits ranging from 0 to 9
}
System.out.println((i) + " counts = " + count);
}
}//end of displayCounts
}//end of class

Categories