This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors.
import java.util.Scanner;
class animals {
public static void main(String[] args) {
int[] q1 = question();
output(q1);
System.exit(0);
} // exit main
public static int[] question() {
String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" };
int number = 0;
int[] record = {};
for (int i = 1; i <= 5; i++) {
System.out.println(wild[number] + ":");
Scanner scanner = new Scanner(System.in);
System.out.println("How many are left in the wild?");
int howMany = scanner.nextInt();
record = new int[] {howMany};
number++;
}//end for loop
return record;
}// end method question
public static void output(int[] q1){
System.out.println("There are " + q1[0] + " Komodo Dragons in the wild");
System.out.println("There are " + q1[1] + " Mantees in the wild");
System.out.println("There are " + q1[2] + " Kakapos in the wild");
System.out.println("There are " + q1[3] + " Florida Panthers in the wild");
System.out.println("There are " + q1[4] + " White Rhinos in the wild");
}//end method output
} // end class animals
So this compiles alright, then when i've added 5 numbers in terminal after each loop i get
There are 3 Komodo Dragons in the wild
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at animals.output(animals.java:39)
at animals.main(animals.java:13)
Other than the fact that im getting the text, the monodo dragon number being provided is the last number i input not the first
This doesn't make sense
int[number] record = {};
most like what you meant was
int[] record = new int[wild.length];
and instead of
for (int i = 1; i <= 5; i++) {
you need
for (int i = 0; i < wild.length; i++) {
instead of the following which creates an array of 1 value [0]
record = new int[] {howMany};
which will produce the following when you try to access [1]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
you need
record[i] = howMany;
As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.
This is what you need:
int number = 0;
int[] record = new int[5];
and another modification which you need to make:
int howMany = scanner.nextInt();
record[number] = howMany;
Remove comment from last line.
Now your program should work fine.
Learn some basic stuff about arrays.
Related
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);
The Code below I tried got to work correctly. When I go to "Run As" in Eclipse, the Console shows nothing and the output is blank. Please help. NOTE I took out the public class & import java because the post wasn't loading the code correctly.
public static void main(String[] args ) {
// Create new Scanner
Scanner input = new Scanner(System.in);
// Set number of students to 10
int numStudents = 10;
// Note
int [][] studentData = new int[numStudents][1];
// loop
for (int i = 0; i > numStudents; i++) {
// Note
boolean classesValidity = true ;
while (classesValidity == false) {
System.out.print("Enter classes and graduation year for student’" +
(i + 1) + " : " );
int numClasses = input.nextInt();
studentData [i][0] = numClasses;
int gradYear = input.nextInt();
studentData [i][1] = gradYear; }
for (int i1 = 0; i > numStudents; i ++) { System.out.println("\n Student " + ( i ) + " needs " +
studentData [i][0]*3 + " credits to graduate in " + studentData [i][1]); }}}}
classesValidity is initialized with true and remains unchanged. In turn the while loop is never executed and the program only iterates through studentData without operating on it.
assignment:
Write a program that reads in integers between 1 and 100 from the user and counts the
occurrences of each number. The user input ends when they enter a 0.
You must use an enhanced for-loop to solve this problem.
If a number occurs more than 1 time use the plural word “times” instead of “time”. Do not display numbers that were not entered.
I know and understand why my code's current output below appears with duplicates. The print logic is inside the for-each loop code block. If I close the code block I am no longer able to use the variables I initialized inside the loop. I have tried everything I can think of. Any suggestions would be appreciated
current output:
- 1 occurs 1 time,
- 1 occurs 2 times
- 2 occurs 1 time
- 2 occurs 2 times
- 3 occurs 1 time
- 3 occurs 2 times
needed output:
- 1 occurs 2 times
- 2 occurs 2 times
- 3 occurs 2 times
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter Integers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
if (numbers[i] == 0) {
break;
}
}
enhancedLoop(numbers);
}
private static void enhancedLoop(int[] numbers) {
int[] counts = new int[101];
for (int value : numbers) {
counts[value]++;
if (value > 0)
if (counts[value]> 1)
System.out.println(value + " occurs " + counts[value]+ " times");
else
System.out.println(value + " occurs " + counts[value] + " time");
}
}
Variables are only available in the block in which they are declared. Move the output after the for loop and iterate over counts to display the values:
for (int i = 0, c = counts.length; i < c; ++i) {
if (counts[i] > 0) {
if (counts[i] > 1) {
System.out.println(value + " occurs " + counts[i]+ " times");
} else {
System.out.println(value + " occurs " + counts[i]+ " time");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter Integers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
if (numbers[i] == 0) {
break;
}
}
enhancedLoop(numbers);
}
private static void enhancedLoop(int[] numbers) {
int[] counts = new int[101];
for (int value : numbers) {
counts[value]++;
if (value > 0)
if (counts[value]> 1)
System.out.println(value + " occurs " + counts[value]+ " times");
else
System.out.println(value + " occurs " + counts[value] + " time");
}
}
You can do this effectively using the below steps:
(1) Identify the unique numbers first
(2) Find the number of times each unique number occurs
So, you need to change your enhancedLoop(int[] numbers) method as shown below to achieve the result:
private static void enhancedLoop(int[] numbers) {
//convert the array to a list to make computations easier by using streams
List<Integer> numbersList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
//Get the unique numbers in the list
List<Integer> uniqueNumbers = numbersList.stream().distinct().collect(Collectors.toList());
//Now find out number of times each each unique number occured
for(int number : uniqueNumbers) {
long times = numbersList.stream().filter(num -> num == number).count();
System.out.println(number+" occurs "+times);
}
}
lets try to do this without lamdas, using simply a hashmap instead of arrays
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
int tmp=0;
System.out.print("Enter Integers:");
//read a maximum of 10 int
for (int i = 0; i < 10; i++) {
tmp = in.nextInt();
//if we read a 0 we quit
if (tmp == 0) {
break;
}
//if we already saw the number we up the counter
if(numbers.containsKey(tmp)){
numbers.put(tmp, numbers.get(tmp)+1);
}else{
//otherwise we just add the new int
numbers.put(tmp, 1);
}
}
//call the print loop
enhancedLoop(numbers);
}
private static void enhancedLoop(HashMap<Integer, Integer> numbers) {
//you print what you counted
for(Map.Entry<Integer, Integer> entry : numbers.entrySet()) {
System.out.print(entry.getKey() + " occurs " + entry.getValue() + " time");
if (entry.getValue()>1)
System.out.print("s");
System.out.println("");
}
}
I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.