import java.util.*;
public class TestScoreTestor {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> score = new ArrayList<Integer>();
// Scanner keyboard = new Scanner(System.in);
Scanner test = new Scanner(System.in);
System.out.println("Enter the scores(enter the input by Ctrl+z): ");
// int a = keyboard.nextInt(); // **** add this to swallow EOL token
while(test.hasNextInt()) {
score.add(test.nextInt());
}
test.close();
System.out.println();
System.out.println(score.size());
// the scores are not involved
for (int i = 1; i <= score.size(); i++) {
System.out.println(score.get(i));
}
Scores grade = new Scores(score);
System.out.println("Your grade: " + grade.getLetterGrade());
}
}
The above is my code and I have a problem of assigning value from Scanner test to ArrayList score. When I run the code, this shows that
Enter the scores(enter the input by Ctrl+z):
90 90 90
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Lab05Q6.Scores.averageScore(Scores.java:29)
at Lab05Q6.Scores.getLetterGrade(Scores.java:36)
at Lab05Q6.TestScoreTestor.main(TestScoreTestor.java:29)
"0" is the size of the arrayList, so I think that there may be some problem during the value adding
while(test.hasNextInt()) {
score.add(test.nextInt());
}
and also I have tried the solutions for others' questions similar to mine,but it does not work. Could you please help me with these question?
Some suggestions and that might help you get it off better :
while(test.hasNextInt()) {
score.add(test.nextInt());
}
This loop will terminate only if you enter some non-digit character. Space and new line will not terminate the loop.
for (int i = 1; i <= score.size(); i++) {
System.out.println(score.get(i));
}
Exception you posted, will never be reached because you will always end up into index out of bound exception. Also, you are starting with index = 1, you might want to start from index 0. Not sure about your logic in Score class.
Also, as what others said, if you posted exception from any class, please provide that.
Related
I just wanted to say first that I'm a beginner so I apologize for my (really) horrible code.
I'm creating a program where you input an int and print out the square root using a do while loop. And when you input "0" the program will stop.
How do you stop it?
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
do {
System.out.println("Please enter an integer.");
int sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot==0);
System.out.println("Closing...");
InputNum.close();
}
}
You need to test if the value entered was 0 (I would test less than or equal to zero, because the square root of a negative number is imaginary). If so, break the loop. Like,
int sqroot = InputNum.nextInt();
if (sqroot <= 0) {
break;
}
try this
public static void main(String[] args) {
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
int sqroot = 0;
do {
System.out.println("Please enter an integer.");
sqroot = InputNum.nextInt();
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
} while (sqroot != 0);
System.out.println("Closing...");
InputNum.close();
}
I just initialize sqroot outside of your while and change == to !=
This academic exercise may demand use of a do/while loop, but if you're not constrained to using it, a for loop would also work:
public static void main(String[] args)
{
Scanner InputNum = new Scanner(System.in);
DecimalFormat formatTenths = new DecimalFormat("0.0");
System.out.println("Please enter an integer.");
for(int sqroot = InputNum.nextInt(); sqroot > 0; sqroot = InputNum.nextInt()) {
double Finalsqroot = Math.sqrt(sqroot);
System.out.println("Your Square Root is: " + (formatTenths.format(Finalsqroot)));
}
System.out.println("Closing...");
InputNum.close();
}
Your program as presented in the question has an intrinsic flaw: you ask for input and then immediately try and do something with it (calc the square root) without determining if it is suitable to use.
Switching to a for loop is one way this can be overcome, because it encourages a program flow of "ask for input", "check if input is acceptable", "use input", "repeat"
If you're constrained to using a do/while loop then you still need to follow this flow, which Elliott Frish addresses in his answer, recommending you add in the "check if input is acceptable" part as a dual purpose test of whether the input is <= 0.. Such values are not acceptable for a square root op, and you also want to end the program when you encounter them, so the test can be used to achieve both goals
Side trivia, for loops can be used pretty much exclusively:
for(;;) //same as while(true)
for(;test;) //same as while(test)
for(bool do = true; do; do = test) //same as do..while(test)
..though using while or do is probably more readable than using a for loop for the same job
Note, your while(sqroot==0) is a bug.. you don't want to continue looping while the user entered 0, you want to continue looping while they DIDN'T enter a 0...
I have a question to do in my Java class, and it asks me to write a program that takes in n numbers from the user and outputs the average of them. I know I could do it a much simpler way, just by asking the user to enter the amount of values (s)he needs to enter at the beginning, but I want to create the program so the user doesn't necessarily have to know the number of values at the beginning.
So for this, I create an array of 100 length (which hopefully covers the amount the user needs to enter) inside a for loop (rendering that 100 length array null after the loop, so the program doesn't become too memory heavy) and running a counter trough each iteration. Once the user enters stop, the loop ends, and the values entered into the 100 length array gets transferred to an array the size of the count.
Here is the code:
import java.util.*;
import java.lang.*;
public class main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
//Question 1
System.out.println("Enter your numbers. (Enter 'Stop' when you're done)");
int temp = 0;
String uInput = "";
char stopper;
int count = 0;
double total = 0;
int a = 0;
boolean inStop = true;
for (boolean stop = false; stop != true;)
{
int array [] = new int [100];
if (inStop == true)
{
System.out.println("point 5");
System.out.print("Input: ");
uInput = input.nextLine(); //reads user input
}
try //empty input repeater
{
System.out.println("point 1");
try //dealing with letters in string instead of numbers
{
System.out.println("point 2");
temp = Integer.parseInt(uInput); //converts string to int
array[count] = temp;
count++;
System.out.println(inStop);
if (inStop == false) //executes when stop has been reached
{
System.out.println("point 3");
int numberArray [] = new int [count]; //fills final array
for (int i = 0; i < count; i++)
{
numberArray[i] = array[i];
}
for (a = 0; a < numberArray.length; a++)
{
total = total + numberArray[a];
}
total = total / a;
stop = true; //ends parent loop
}
}
catch (NumberFormatException e) //catches letters in string and checks for stop
{
System.out.println("point 4");
stopper = uInput.charAt(0);
stopper = Character.toUpperCase(stopper);
if (stopper == 'S')
{
inStop = false;
System.out.println("point 6");
}
}
}
catch (StringIndexOutOfBoundsException e)
{
}
}
System.out.println("The average of the values entered is: " + total + ".");
}
}
The problem is, as you can see there are numerous numbered printouts that indicate (to me) where the program is at the moment. All runs fine, except for point 3. Point 3 for some reason doesn't execute whatsoever. No matter what I do. Now, the problem lies on line 34, temp = Integer.valueOf(uInput); //converts string to int
If I put in a print function directly after that line, that position doesn't print onto the screen. I believe there are no syntax or logic errors with that part, and so does my lecturer, however the code still doesn't execute and the program loops infinitely afterwards. Something is breaking either temp or uInput in that line and we cannot figure out what. I have compiled and ran the code through a different compiler to what I initially used and even tried in the Command Prompt with the same results (so it is not the IDE causing the issue).
Any insight we may have missed would be appreciated. Thanks.
p.s.: don't knock my lecturer, he didn't write the code, and it isn't that easily readable. He could easily know what the problem is, if not for any error in my explanations or his interpretations of how my program is meant to run.
I think that the reason you are having a problem identifying the issue is because of your code structure.
You have mixed the logic for informing the use, with the logic for reading the inputs, and calculating.
If your main method only deal with informing the user, and relies on another method to calculate the average,and another to read the user's input everything will be easier to read, follow and see that you are parsing "stop" as an int.
public static void main(String[] args) {
System.out.println("instructions");
int[] all = readUserInputs();
double ave = calculateAverage(all);
System.out.println("message " + ave);
}
private static double calculateAverage(int[] numbers) {
// I will leave it to you to fill this out
return yourValue;
}
private static String readUserInputs() {
Scanner input;// as above
int[] values; // is an array best? What about a List?
for (int i = 0; ; i++) {
String line = input.nextLine();
if ("stop".equals(line) {
break;
}
//try to parse and put into array/list
}
return values;
}
Hopefully you will find this easier to read and work with,I have left a few gaps for you to fill in.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently doing a college lab on while loops and I'm stuck and would appreciate any help available. I have to write a program as follows
Write a program MaxNum that reads in a sequence of 10 positive integers, and
outputs the maximum of the sequence
Now I could just make 10 ints and make the user input a value but I'm not sure how to do that with a while loop?
Here is the code I have at the moment :
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
System.out.println("Please enter 10 integers");
do
{
for(Num1 = 0; Num1 < 10; Num1++);
{
Num1 = in.nextInt();
}
}
while(Num1 > 0);
}
}
Since you can't use array, you just use a max to check if the number entered is bigger than the previous number entered. You don't need a while loop, at least your do-while is not really needed in this case.
Edit: don't modify num1, you will be messing around with your for-loop
import java.util.Scanner;
public class SumTenNumbers{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int Num1= 0;
int max = 0;
int userInput = 0;
System.out.println("Please enter 10 integers");
for(Num1 = 0; Num1 < 10; Num1++);
{
userInput = in.nextInt();
if(num1 == 0){//you set your first number as the maximum
max = userInput;
}else if(max < userInput){
max = userInput;//here you set the number to max
}
}
}
}
Here is something you could do since you explicitly saying you are learning the while loop. You can keep getting user's input until you have enough number of Integers entered, since you mentioned you only want Integer. And you can use Collections.max at the end.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (list.size() < 10 && scanner.hasNext()) {
if (scanner.hasNextInt()) {
list.add(scanner.nextInt());
} else {
scanner.next();
}
}
Integer max = Collections.max(list);
System.out.println(max);
}
I am a newbie and i have no idea what is wrong with my code here. I am going to write both the questions and my code here. Please if anyone can help me.
So the question says:
You have to tell the total number of chores the person can perform in the given time.
The first input is the total number of time the user got.
The second input is the total number of chores the user wants to perform.
The final inputs is the time it will take to complete each task.
and here goes my code:
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int totalmins, chores=0, eachtime, totalchores, counter=0;
// getting the input
System.out.println("Enter the total time:");
totalmins=scan.nextInt();
while (totalmins>100000) {
System.out.println("Enter again. Less than 100000:");
totalmins=scan.nextInt();
}
System.out.println("Enter the total chores:");
chores=scan.nextInt();
int [] time = new int[chores];
for (int i=1; i<chores; i++) {
System.out.println("Enter time:");
eachtime=scan.nextInt();
time[i]=eachtime;
}
// arranging in ascending order
for (int i=0;i<time.length; i++) {
if (time[i] > time[i+1]) {
int temp = time[i];
time[i]=time[i+1];
time[i+1]=temp;
}
}
for (int i=0;i<time.length; i++) {
totalchores=time[i] + time[i+1];
counter++;
if (totalchores>totalmins) {
counter=counter-1;
System.out.println(counter);
}
}
}
I think the point that you're missing is that in an array of length 3, the entries are numbered 0, 1 and 2. If you try to use entry number 3, you'll get that exception. But that's exactly what you're doing - all of your loops continue until i = 2 (including that case), but then you go ahead and try to use entry i + 1 of the array.
I am a beginner in Java and had a question regarding an assignment I was doing.
I am trying to read a sequence of integer inputs and print out the largest and the smallest number. Though I already wrote the code, but the problem is that when I run it, it doesn't print the largest nor the smallest number. The code seems right even though its not! Any help would be appreciated.
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integers: ");
int largest = in.nextInt();
int smallest = largest;
while (in.hasNextInt()) {
int input = in.nextInt();
if (input > largest) {
largest = input;
} else if (input < smallest) {
smallest = input;
}
System.out.println();
}
System.out.println(largest);
System.out.println(smallest);
}
}
To Stop Waiting for an input :
Enter A character as input : in.hasNextInt() return False
Your code will not stop accepting numbers until it get something other than a number.
Like a alphabetical character. Enter an alphabetical character or keep something as a terminator.
Like enter -99 to quit or something.
Reading the code I would say that you expect the user to enter a set of numbers separated by space (the default separator chosen by the Scanner)
The scanner will loop endless parsing the input.
Now you need to decide a condition to exit and make your code safer.
When I say make your vode safer I mean put a try catch around your code in case the user doesn't write a number. Moreover you should close the scanner in a finally.
If you write something like the code below, the cycle is broken whenever u write a letter. E.g 1 2 4 6 A will print 2 and 6. Take it as a suggestion to work out a bit. Actually. you need to still protect the first nextInt, which, as it is, could throw exception if you don't start with a number and ideally decide an exit character handling the other exceptions. But these are implementation details. The code below will work provided that you start with a number and finish with a character different from a number
import java.util.Scanner;
public class Practise {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter integers: ");
int largest = in.nextInt();
int smallest = largest;
try {
while (in.hasNextInt()||in.hasNext()) {
int input = in.nextInt();
if (input > largest) {
largest = input;
} else if (input < smallest) {
smallest = input;
}
System.out.println("Computing "+input);
}
System.out.println(largest);
System.out.println(smallest);
} catch (Exception ex) {
System.out.print("Exception caught: " + ex);
} finally {
in.close();
}
}
}