ArrayLists not adding values properly? [duplicate] - java

This question already has answers here:
Scanner input accepting Strings skipping every other input inside a while loop. [duplicate]
(3 answers)
Closed 7 years ago.
Everything compiles, but when I print the size and the array elements, it indicates that not all of the values are added in because the size and the values would only be partial. Also, sometimes the sentinel value does not work( I have to enter it twice at times).What's wrong?
import java.util.ArrayList;
import java.util.Scanner;
public class BowlingScoresArrayList{
public static final int SENTINEL = -999;
public static final int MIN=-1;
public static void main (String [] Args) {
ArrayList<Integer> bowlingScores = new ArrayList<Integer>();
Scanner reader = new Scanner(System.in);
System.out.println("Enter your scores: ");
do {
bowlingScores.add(reader.nextInt());
} while (reader.nextInt()!= SENTINEL);
System.out.println(bowlingScores);
System.out.println(bowlingScores.size());
So I tried entering these values:
Enter your scores:
1
2
2
3
-999
-999
And it yields this:
[1, 2, -999]
3

You're problem is, you're using two nextInt statements...
do {
bowlingScores.add(reader.nextInt());
} while (reader.nextInt()!= SENTINEL);
So you're asking the user to provide input twice.
Instead, something like...
int in = SENTINEL;
do {
in = reader.nextInt();
if (in != SENTINEL) {
bowlingScores.add(in);
}
} while (in != SENTINEL);
would produce the desired results

Related

Java ,Stack Calculator works fine if I manually push values to stack, but not if I push them using Scanner [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have to to a calculator that adds, subtract, multiply and divide the numbers one by one to a stack, and at the end it will show the result of all operations. Example.
Input:10
Input:+
Input:10
Input:=
Output: 10+10=20
I tried to do it by manually pushing the numbers and operators, and it worked fine, for adding and subtracting only. (here is the code).
public static void main(String[] args) {
Stack<String> stack = new Stack();
stack.push("10");
stack.push("+");
stack.push("10");
stack.push("-");
stack.push("20");
stack.push("+");
stack.push("1");
stack.push("=");
int result=0;
int i;
int result=0;
for(i=0;i<stack.size();i++){
if (stack.elementAt(i)== "+"){
//does get in
I checked in the second code that the stack is similar to the one on the first code, and it is similar. For some reason, it doesn't want to go through the if statement, even though it is equal to "+" or "-".
Stack<String> stack = new Stack();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String s1 = sc.next();
stack.push(s1);
if(s1.equals("=")) {
break;
}
}
int i;
int result=0;
for(i=0;i<stack.size();i++){
System.out.print(stack.elementAt(i));
}
for(i=0;i<stack.size();i++){
if (stack.elementAt(i)=="+"){
//doesn't get in
The problem with your code is in this line
if (stack.elementAt(i)== "+")
The stack takes String types of arguements. For comparision you should use
if(stack.elementAt(i).equals("+"))
Similarly , do the same for "-".

Sorting names and using JOptionPane to show output [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
So my code so far is this...
import javax.swing.*;
public class TestNo2{
public static void main(String[] args){
String[] nameNum = new String[0];
int numberNames;
JTextField inputName = new JTextField(5);
JPanel nameWindow = new JPanel();
nameWindow.add(new JLabel("How many names would you like to sort?"));
nameWindow.add(inputName);
int numNames = JOptionPane.showConfirmDialog(null, nameWindow
,"Accept and sort list of students."
,JOptionPane.OK_CANCEL_OPTION);
if(numNames == JOptionPane.OK_OPTION){
String numNamesS = inputName.getText();
numberNames = Integer.parseInt(numNamesS);
nameNum = new String[numberNames];
for(int counterOne=0;counterOne<nameNum.length;counterOne++){
for(int counterTwo=1;counterTwo<=nameNum.length;counterTwo++){
nameNum[numberNames] = JOptionPane.showInputDialog(null
,"Enter the name of student "+counterTwo
,"Name Input"
,JOptionPane.QUESTION_MESSAGE);
}
}
}
}
}
There's no error when I build it but when I run the program, I would only be allowed to enter one name then the error occurs.
This is the error that shows up.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at TestNo2.main(TestNo2.java:23)
Thank you for your time in reading this.
for(int counterTwo=1;counterTwo<=nameNum.length;counterTwo++){
should be:
for(int counterTwo=1;counterTwo < nameNum.length;counterTwo++){
Because the expression counterTwo<=nameNum.length causes the array to exceed its bounds (remember that actual length of array starts from zero and is 1 Less than actual length you specified.
So if you have an array defined like:
someArray[] something = {1,2,3,4,5,6};
The value of something.length would be 6. But the actual length is 5 (Counting as: 0,1,2,3,4,5).
And why do you have two loops for just gettings names and adding to String Array? Just one is enough...
for(int counterOne=0;counterOne<nameNum.length;counterOne++){
nameNum[counterOne] = JOptionPane.showInputDialog(null
,"Enter the name of student "+(counterOne+1)
,"Name Input"
,JOptionPane.QUESTION_MESSAGE);
}
And then sort the array nameNum with whatever method you plan to use.

Reading certain integers from a text file into a Array List

I have to read two sets of integers in a text file. One is the number of credits that a student can have and then the next integer is a letter grade on a test. I can read the integers into an ArrayList, but the issue is that I want to read first the amount of credit they have, then choose which ArrayList to add them to, under a certain amount of credit or over a certain amount. I don't want to add the amount of credits up, just the grade they received. I have 25 lines of integers in the text file, first is the amount of credit, then a space, and then the grade. I only need to record the grade, not the credit amount.
Here is what my code looks like so far:
public static void main(String[] args) throws FileNotFoundException
{
try
{
ArrayList <Integer> over15credits = new ArrayList<>();
ArrayList <Integer> under15credits = new ArrayList<>();
FileReader myReader = new FileReader("geomClass.txt");
Scanner fileIn = new Scanner(myReader);
while(fileIn.hasNextInt())
{
if(fileIn.nextInt() >= 15)
{
over15credits.add(fileIn.nextInt());
}
else
{
under15credits.add(fileIn.nextInt());
}
System.out.println(over15credits);
System.out.println(under15credits);
}
}
catch(FileNotFoundException e)
{
System.out.println("!!FILE NOT FOUND!!");
}
}
When you perform fileIn.nextInt() it reads and consumes the number so that when you call fileIn.nextInt() again it will read the number after that.
Most likely you meant to use a variable so that you can use the number you just read.
int num = fileIn.nextInt();
if (num >= 15)
over15credits.add(num);
else
under15credits.add(num);
You want to use the same number you just read not another number.
FYI you can also write it like this.
int num = fileIn.nextInt();
(num >= 15 ? over15credits : under15credits).add(num);

Java: Saving User Input to be Calculated in a Loop

Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);

Exception in thread ArrayIndex

I was doing some beginner programming with series and input but im having the same problem constantly.Cant find the solution.Basically what i want my program to do for now i input a list of numbers and print them out.And im getting the same error over and over whatever i change in program.Here is my code.
import java.util.Scanner;
public class Test437 {
public static void main(String[] args) {
int limit = 25;
int cnt;
int addtion;
double dbt; //Devided by two % 2
Scanner input = new Scanner(System.in);
int [] ya = new int[8];
for(cnt = 0;cnt < ya.length;cnt++)
{
System.out.print("ya[" + cnt + "]= ");
ya[cnt] = input.nextInt();
}
System.out.println(ya[cnt]);
}
}
Im getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at Test437.main(Test437.java:22)
System.out.println(ya[cnt]); this line is outside loop. Cnt is equal to an array size so it cannot be used in such way because there is no element in the array with such index.
The line:
System.out.println(ya[cnt]);
needs to be in a loop again to print out all the array values after accepting them:
for (cnt = 0;cnt < ya.length;cnt++) {
System.out.println(ya[cnt]);
}
Alternatively, you could do:
System.out.println(Arrays.toString(ya));
cnt condition to leave the loop is to exceed the length therefore you get in indexoutofbounds
This line
System.out.println(ya[cnt]);
is trying to access element at ya.Length index which does not exists.
In your example ya[8] contains elements at position from 0 to 7 (ya[0] ya[1] ... ya[7] and you're trying to access ya[8] bacuase cnt variable is 8 after the for statement ends.
Therefore the compiler throws an indexOutOfBounds exception.

Categories

Resources