My question is what they do " smallest" variable and the if statement. I know what the program do but it cost me to understand well the flow execution of this part .
import java.util.Scanner;
import java.util.ArrayList;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while(true){
int numbers = Integer.valueOf(reader.nextLine());
if(numbers == 9999){
break;
}
list.add(numbers);
}
int index;
int smallest = list.get(0);
for (int i = 0; i < list.size();i++){
int number = list.get(i);
if ( smallest > number){
smallest = number;
}
}
System.out.println(smallest);
}
}
This is a rather simple console application. You should try to read your code line by line when you are starting to learn a new language.
This way you can show some effort and ask more clear and concise questions. Here is an example to go about reading your code line by line. If you don't know what some function is doing, look up that function.
Just take your time, you'll get used to the syntax and it will get easier every time.
Scanner reader = new Scanner(System.in); // Create scanner taking console inputs
ArrayList<Integer> list = new ArrayList<>(); // Create list
while(true){ // Endlessly loop
// Keep reading input from console until user inputs 9999, then break
int number = Integer.valueOf(reader.nextLine());
if(number == 9999){
break;
}
list.add(number); // Add number to list
}
/* int index; // This is worthless, not used again */
int smallest = list.get(0); // Variable to store smallest number
for (int i = 0; i < list.size();i++){ // Increase i until list size is reached
int number = list.get(i); // Get number for position i in list
if ( smallest > number){ // Compare
smallest = number; // Set new smallest number
}
}
System.out.println(smallest); // Print
Related
I have a data file that consists of a calorie count.
the calorie count it separated by each elf that owns it and how many calories are in each fruit.
so this represents 3 elves
4323
4004
4070
1780
5899
1912
2796
5743
3008
1703
4870
5048
2485
1204
30180
33734
19662
all the numbers next to each other are the same elf. the separated ones are seperate.
i tried to detect the double line break like so
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String [] args) throws FileNotFoundException
{
int[] elf = new int[100000];
int cnt = 0;
Scanner input = new Scanner(new File("Elf.dat"));
while(input.hasNext())
{
elf[cnt] += input.nextInt();
if (input.next().equals("\n\n"));
{
cnt++;
}
}
int big = elf[0];
for (int lcv = 0; lcv < elf.length; lcv++)
{
if (big < elf[lcv])
{
big = elf[lcv];
}
}
System.out.println(big);
}
}
I'm trying this to detect the double line break
if (input.next().equals("\n\n"));
but its giving me errors. how would i detect it
Here is another alternative way to do this sort of thing. read comments in code:
public static void main(String[] args) throws FileNotFoundException {
List<Integer> elfSums; // Can grow dynamically whereas an Array can not.
int sum;
// 'Try With Resources' used here to auto close the reader and free resources.
try (Scanner input = new Scanner(new File("Elf.dat"))) {
elfSums = new ArrayList<>();
String line;
sum = 0;
while (input.hasNextLine()) {
line = input.nextLine();
if (line.trim().isEmpty()) {
elfSums.add(sum);
sum = 0; // Reset sum to 0 (new elf comming up)
}
// Does the line contain a string representation of a integer numerical value?
if (line.matches("\\d+")) {
// Yes...add to current sum value.
sum += Integer.parseInt(line);
}
}
}
if (sum > 0) {
elfSums.add(sum);
}
// Convert List to int[] Array (There are shorter ways to do this)
int[] elf = new int[elfSums.size()];
for (int i = 0; i < elfSums.size(); i++) {
elf[i] = elfSums.get(i);
// For the heck of it, display the total sum for this current Elf
System.out.println("Elf #" + (i+1) + " Sum: -> " + elf[i]);
}
/* The elf[] int array now holds the data you need WITHOUT
all those empty elements with the array. */
}
Welcome to Advent of Code 22.
As a good rule, never mix nextXXX methods with any other next.
To break up the Blocks you have 2 good options:
Read line by line and fill a new list when you encounter a empty/blank line
Read the whole text fully, then split by the \n\n Combination
My code will not compile and I can not figure out how to fix the error. It is a compile time run error I think. My error is in my method to print out array. Then, it says that there is something wrong with my closing bracket for the class. I am using a scanner class and I did import it, it is just not shown. Any help?
My code:
public static void main (String[] args){
int[] getArray; //reference to an int array of type and takes no parameters
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
int[] nums; //reference to nums array of type int
nums = new int[size]; /* new array of type int. assigned to nums.
size, to specify number of elements array will have */
for(int i=0; i<nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt(); //storing user input into array
return nums;
}//closing for loop
int[] minimumValue;
min = scan.nextInt();
min = nums[0]; //assigning min value to first element in array
return min;
for(int i=0; i<min.length; i++){
if(i<min){
min = nums[0];
}
}
return min;
public static void printArray (int[] getArray){ //method to print out array
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length); //print out array
}
}
public static void printArrayInReverse(int[] getArray){ //method for arrayInReverse
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
int[] numbers = getArray();// calling getArray method
public static void main (String[] args){
System.out.print("************");
printArray(numbers); //calling printArray method and passing numbers through it
printArrayInReverse(numbers);// calling printArrayInReverse method and passing numbers through it
System.out.print(minimumValue(numbers)); /* calling minVal through print statement and passing
numbers through it*/
}
}
}
It is very hard to tell what you are trying to accomplish here from your code. There is no class here which means your program will not even compile, please remember to post all applicable code to your question as it makes it easier for people to help you.
Firstly, you can only have one entry point (ie. main(String[] args) for each class. This is better explained here Can there exist two main methods in a Java program?.
Within this main method, you cannot have any other methods, you can only call other methods and perform operations ad such.
The variable "scan" cannot ever do anything if it is not instantiated prior to use. The variable getArray is being used as a method, which it is not.
Please take a look at Simple Java array program where it shows more in-depth how to use arrays.
Take a look at this as see if it even accomplishes what you want to do, which is still somewhat unclear. I shortened everything so that it is simpler, with a program this small multiple methods are not needed unless there is some logic to denote when to print the array or when to print the array reversed.
import java.util.Scanner;
public class CLASSNAME {
static Scanner scan = new Scanner(System.in);
static int[] nums;
public static void main(String[] args){
// Get Size Of Array
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
nums = new int[size];
// Fill Array
for(int i = 0; i < nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt();
}
// Set 0th Number To
System.out.println("Enter 0th Number");
int min = scan.nextInt();
nums[0] = min;
// Print Array
System.out.println("\n" + "Printing Array Index 0 -> ArraySize");
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length);
}
// Print Array Reversed
System.out.println("\n" + "Printing Array Index ArraySize -> 0");
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
}
you need to create a Scanner object to use it
you can't create more than one main method
you must create methods outside the main method
Example:
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//code here
}
public static void method_name() {
//code here
}
//If you want to return integer value for example
public static int method_name() {
//code here
}
}
I really need help with my program. I'm trying to make a cumulative grade calculator in java, using arrays and dialog boxes. For some reason, my arrays won't print out the input made by the user which is throwing off my calculations. How can I give it the correct value?
{
// First array - Length
int[] arNumber = null;
int number;
String str;
// Second array - Elements
int numbers;
int[] arNumbers = null;
int total = 0;
int gradeSum = 0;
String str2;
String message = "How many grades will you input in this class?";
str = JOptionPane.showInputDialog(message);
number = Integer.parseInt(str);
arNumber = new int[number];
for(int index = 0; index < arNumber.length; index++)
{
String message2 = "Insert your grade";
str2 = JOptionPane.showInputDialog(message2);
numbers = Integer.parseInt(str2);
arNumbers = new int[numbers];
}
for (int element : arNumbers)
{
// Print array onto console
System.out.println(element);
// Add all elements
gradeSum += element;
// Print grade onto console
System.out.println(gradeSum);
}
total = gradeSum / arNumber.length;
return total;
}```
It looks like you don't need to use two arrays. The line with arNumbers = new int[numbers]; means that arNumbers is getting reinitialized as a new array for every iteration of that loop. Try using arNumber[index] = numbers; to assign the user-entered value into the arNumber array and do away with arNumbers. Then loop over arNumber in the second loop.
Also note that total is declared as an int which will truncate your floating point value, which I'm guessing you don't want. Good luck!
My program compiles, but when I run it, it gives me an IndexOutOfBoundsException. I am wondering what is wrong with it as I am unable to see it. My program is supposed to take input by the user and add it to the ArrayList. I am sorry if my mistake is obvious to you, but I am relatively new at using ArrayLists. Thanks!
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
int counter = 0;
int i = 0;
Scanner in = new Scanner(System.in);
int input = in.nextInt();
while(i < 5)
{
input = in.nextInt();
if(input != 0){
arr.get(i).set(counter++, input);
}
else{
arr.get(i).set(counter++, input);
i++;
counter = 0;
}
}
System.out.println(arr);
When you create your ArrayList of ArrayLists, initially, there are no ArrayLists contained in arr. So any call to get will fail with a IndexOutOfBoundsException.
First, add the initial inner ArrayList to arr.
Then, in the while loop, get the current inner ArrayList as you're doing, but just call add to append a number to the end of the list. Otherwise, you'll get a IndexOutOfBoundsException on your inner ArrayList. Again, the ArrayList you've created is initially empty.
When the user enters 0, then add another ArrayList when you're incrementing i (unless i is already at the last desired value), to prepare for the user adding numbers to the next list.
You are creating a list of list and both are empty. Also you are using "set" method which is actually used to replace the object in a list on specific location.
So it looks like you wanted to take input from user and if the value is 0 you just wanted to ignore it. Below is the update example for you.
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
int i = 0;
Scanner in = new Scanner(System.in);
int input = 0;
while(i < 5){
input = in.nextInt();
if(input != 0){
arr.add(new ArrayList<Integer>());
arr.get(i).add(input);
i++;
}
}
System.out.println(arr);
If you just want to create a list of integers then you don't have need to create a list of list. You can achieve by creating a list of integer only.
ArrayList<Integer> arr = new ArrayList< Integer >();
int i = 0;
Scanner in = new Scanner(System.in);
int input = 0;
while(i < 5){
input = in.nextInt();
if(input != 0){
arr.add(input);
i++;
}
}
System.out.println(arr);
I have a quick question I have a program I am writing in java, it takes a .txt file reads what is inside it(this case it being a bunch of numbers) the program stores it in an array, then it sorts it from least to greatest it also finds the average as well as it tells me how many numbers in the array are bigger than the average. I have managed to do all of that but what I am having trouble with is now I want the program to print out another .txt file but this time with the results of my program. I want it to print out the sorted array the average the number of how many elements are in the array as well as the number of numbers bigger than the average. here is my code that i have:
import java.util.Scanner;
import java.util.Arrays;
class numberSorter{
public static void main (String[]args)throws Exception{
//calling the .txt file
java.io.File file= new java.io.File("numTestData.txt");
java.io.File file2=new java.io.File("dataOut.txt");
Scanner input = new Scanner(file);
//getting the numbers from the file
int num=input.nextInt();
//starting variables
int ct=0;
int bigger=0;
double average;
double track=0;
double[]numberArray=new double[num];
//filling in the rest of the numbers in the array
for(int i =0; i < numberArray.length; i++){
numberArray[i] = input.nextInt();
}
input.close();
//calling the sort method to sort the array
sort(numberArray);
//tracking how many elements are in the array
for(int i=0;i<numberArray.length;i++){
track+=numberArray[i];
}
//finding the average of the sorted array
average=track/numberArray.length;
//looking through the array to find which number is bigger than the average
for(int i=0;i<numberArray.length;i++)
{
if(numberArray[i]>average)
bigger++;
}
//checking to see of the .txt file exists
if(file2.exists()){
System.out.println("file exists");
System.exit(0);
}
//creating a file
try(
java.io.PrintWriter output=new java.io.PrintWriter(file2);
){
//printing out to the .txt file
output.println("Number of slots:");
output.println(numberArray.length);
output.println("sorted:");
for(int i =0; i < numberArray.length; i++){
output.println(numberArray[i]);
}
output.println("Average:");
output.println(average);
output.println("number of above average values: ");
output.println(bigger);
}
}
//sort method
public static void sort(double[]arrange)
{
//looking for the smallest number
for(int i=0;i<arrange.length-1;i++){
double currentMin=arrange[i];
int currentMinIndex=i;
//checking to see if the current number is smaller or bigger
for(int j=i+1;j<arrange.length;j++){
if(currentMin>arrange[j]){
currentMin=arrange[j];
currentMinIndex=j;
}
}
//will arrange the numbers if current number is not smaller
if(currentMinIndex!=i){
arrange[currentMinIndex]=arrange[i];
arrange[i]=currentMin;
}
}
}
}
Now my question is i keep getting this error, everything complies but when I try to run it i come across this:
----jGRASP exec: java numberSorter
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at numberSorter.main(numberSorter.java:26)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Ive tried to mees around with the code but I still keep getting this any help please? I am still learning java
To get rid of errors related to a not matching int in the first line, i would recommend not using this first int counting the numbers, you want to parse.
So your input file would be:
12345 23456 123 4567 123456 7654 999 3453 997733 43 654321
You could use an ArrayList instead of an array and then go through the file with input.hasNext().
I updated the parts in your code:
import java.util.ArrayList;
import java.util.Scanner;
public class NumberSorter {
public static void main(String[] args) throws Exception {
// calling the .txt file
java.io.File file = new java.io.File("numTestData.txt");
java.io.File file2 = new java.io.File("dataOut.txt");
Scanner input = new Scanner(file);
int bigger = 0;
double average;
double track = 0;
ArrayList<Double> numberArray = new ArrayList<Double>();
while (input.hasNext()) {
numberArray.add(input.nextDouble());
}
input.close();
// calling the sort method to sort the array
sort(numberArray);
// tracking how many elements are in the array
for (int i = 0; i < numberArray.size(); i++) {
track += numberArray.get(i);
}
// finding the average of the sorted array
average = track / numberArray.size();
// looking through the array to find which number is bigger than the
// average
for (int i = 0; i < numberArray.size(); i++) {
if (numberArray.get(i) > average)
bigger++;
}
// checking to see of the .txt file exists
if (file2.exists()) {
System.out.println("file exists");
System.exit(0);
}
// creating a file
try (java.io.PrintWriter output = new java.io.PrintWriter(file2);) {
// printing out to the .txt file
output.println("Number of slots:");
output.println(numberArray.size());
output.println("sorted:");
for (int i = 0; i < numberArray.size(); i++) {
output.println(numberArray.get(i));
}
output.println("Average:");
output.println(average);
output.println("number of above average values: ");
output.println(bigger);
}
}
// sort method
public static void sort(ArrayList<Double> arrange) {
// looking for the smallest number
for (int i = 0; i < arrange.size() - 1; i++) {
double currentMin = arrange.get(i);
int currentMinIndex = i;
// checking to see if the current number is smaller or bigger
for (int j = i + 1; j < arrange.size(); j++) {
if (currentMin > arrange.get(j)) {
currentMin = arrange.get(j);
currentMinIndex = j;
}
}
// will arrange the numbers if current number is not smaller
if (currentMinIndex != i) {
arrange.set(currentMinIndex, arrange.get(i));
arrange.set(i,currentMin);
}
}
}
}