I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement
Related
Problem:
How do I reprint the for-loops output, outside the loop? Need help to figure it out. what seems to be the error?
Research effort:
**import java.util.*;
public class Admin {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList <String> title = new ArrayList<>();
String n = in.nextLine();
int i = 0;
int j = 0;
while(!n.equals(" ")){
System.out.println("Enter a movie title");
title.add(n);
n = in.nextLine();
}
for(;i < title.size(); i++){
System.out.println("[" + i +"]" +title.get(i));
}
int [] price = new int [title.size()];
for(;j < price.length; j++ ){
System.out.println("Enter price for");
price[j] = in.nextInt();
System.out.println("Price for ["+j+"] is "+ price[j] );
}
//the problem
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
}
}
every time I run it after the loops, error shows up
Expected Result: is that it will print the "i" and "title[i]" together with the "j" and "price[j]" both outside it's loops
If I understood you correctly you want to see something like this:
[0]MovieTitle1 Price: MoviePrice1
[1]MovieTitle2 Price: MoviePrice2
There are some Problems: At first, you are going to get an IndexOutOfBoundsException,
because i and j have been increased to title.size(). This is because of the two for-Loops.
In my example this means that i == 2 and j == 2 are true after execution of both for-Loops has happened.
The title ArrayList and the price Array know the Entrys 0 and 1 (in my example) - you are trying to access Entry 2 which is out of bounds.
A possible solution would be to change this:
System.out.println("["+ i+"]"+title.get(i)+" Price: "+price[j] );
to something like this:
for(int n = 0; n < title.size(); n++) {
System.out.println("[" + n + "]" + title.get(n) + " Price: " + price[n]);
}
This is a program that list several facts about an integer input from a Scanner object. However, I'm having some trouble with the if/else statement at the end.
The problem is if the input is a positive integer other than 0, the program always reads this statement: System.out.println("j) It is smaller than its reverse value: " + reverse);. If it's a negative int, it always prints System.out.println("j) It is bigger than its reverse value: " + reverse);.
I think it's because the data that's stored in reverse is 0, because int reverse = 0; is declared before the while loop. However, the program properly prints the reverse of the input.
import java.util.Scanner;
public class Integer {
public static void main(String[] args) {
System.out.println("This program will:");
System.out.println("1) Prompt you for an integer then \n2) List several facts about that integer");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
System.out.print("\nEnter an integer: "); // prompt the user to enter an integer
while ( ! keyboard.hasNextInt()) { // is the first input value an int?
String badInput; // assign non-integer inputs to badInput
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.print("Please enter an integer: ");
}
int integer = keyboard.nextInt(); // assign the input to the integer variable
System.out.println("A list of several facts about the number: " + integer); // safe to read first input value
System.out.println("================================================================");
// print the input with space betweeen each digits
System.out.print("a) The digit(s) in it is/are: ");
String number = String.valueOf(integer);
for ( int count = 0; count < number.length(); count++) {
char counted = number.charAt(count); // read each digit in the input
System.out.print(counted + " ");
}
System.out.println(); // skip a line
// determine whether the input is negative or positive
if ( integer >= 0 ) {
System.out.println("b) It is positive");
}
else {
System.out.println("b) It is negative");
}
// determine whether the input is even or odd
if (integer % 2 == 0) {
System.out.println("c) It is even");
}
else {
System.out.println("c) It is odd");
}
int countOdd = 0;
int countEven = 0;
int countDigit = 0;
int countZero = 0;
int reverse = 0;
int sum = 0;
int product = 1;
int readRightMost;
while(integer != 0) {
readRightMost = integer % 10; // read rightmost digit in the input
reverse = reverse * 10 + readRightMost;
integer /= 10; // drop the rightmost digit in the input
++countDigit;
sum += readRightMost;
product *= readRightMost;
if (readRightMost % 2 == 0){ // count how many even digits are in the input
++countEven;
}
else { // count how many odd digits are in the input
++countOdd;
}
if (readRightMost == 0) { // count how many zero digits are in the input
++countZero;
}
}
System.out.println("d) It has " + countDigit + " digit(s)");
System.out.println("e) It has " + countOdd + " odd digit(s)");
System.out.println("f) It has " + countEven + " even digit(s)");
System.out.println("g) It has " + countZero + " zero digit(s)");
System.out.println("h) The sum of the digits in it is " + sum);
System.out.println("i) The product of the digits in it is " + product);
if (integer < reverse) { // if the reverse value of an int is greater than its original value
System.out.println("j) It is smaller than its reverse value: " + reverse);
}
else { // if the reverse value of an int is lesser than its original value
System.out.println("j) It is bigger than its reverse value: " + reverse);
}
System.out.println("================================================================");
}
}
At the end of your while(integer != 0) loop, you know integer must be 0, and you never change it again before your if (integer < reverse), so it may as well be if (0 < reverse), which has exactly the behavior you're seeing. To fix it, make your loop operate on a different variable than you test later.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Need to get that negative number to iterate from -2345 to 2 3 4 5 then it sums to 14. The part I can't figure out is the 2 3 4 5 comes out as -2 3 4 5...syntax I'm missing?? Maybe it is just a line of code or a for statement...
import java.util.*;
public class sumofNumbers{
static Scanner console = new Scanner(System.in);
public static void main(String[] args){
int input;
int sum = 0;
int strnbr = 0;
int counter = 1;
String nbr = "";
System.out.print("enter a number: ");
input = console.nextInt();
if (input == (-input)) {
input = input * (-1);
nbr = String.valueOf(input);
strnbr = nbr.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
} else {
nbr = String.valueOf(input);
strnbr = nbr.length();
System.out.print("the digits of " + input + " are: ");
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.err.println();
System.out.println("the sum is: " + sum);
}
}
}
Comments to your code:
if (input == (-input)) can only be true for 0 and Integer.MIN_VALUE, two fringe cases you probably don't care about. Looks like you meant if (input < 0).
input = input * (-1) is better written as input = -input.
With the above, the if and the else blocks become the same, so you only need the if to do the input = -input.
You can even do that without if by always doing input = Math.abs(input).
counter is unnecessary. You should use substring(i, i + 1) since that is what you really mean.
substring(i, i + 1).charAt(0) is the slow way to write charAt(i).
To iterate all the characters of a String, you can call toCharArray() and use an enhanced for loop.
In print(var + " ") it doesn't matter whether var is a String of one digit, a char with the digit, or an int with the digit. The result is the same.
Since nbr will only contains the characters '0' to '9', Character.getNumericValue(ch) is the slow way to say ch - '0'.
sum = sum + digit can be shortened to sum += digit.
Don't print to System.err.
Java naming convensions state that class names should start with uppercase letter.
Don't pre-declare your variables. Declare them where they are needed. This often also help reduce their scope.
Applying all of that, changes your code to:
public class SumOfNumbers {
static Scanner console = new Scanner(System.in);
public static void main(String[] args){
System.out.print("enter a number: ");
int input = console.nextInt();
System.out.print("the digits of " + input + " are: ");
String nbr = String.valueOf(Math.abs(input));
int sum = 0;
for (char ch : nbr.toCharArray()) {
System.out.print(ch + " ");
sum += ch - '0';
}
System.out.println();
System.out.println("the sum is: " + sum);
}
}
Sample output:
enter a number: -2345
the digits of -2345 are: 2 3 4 5
the sum is: 14
replace your code starting with
if (input == (-input)) {
with
System.out.print("the digits of " + input + " are: ");
input = Math.abs (input);
nbr = String.valueOf(input);
strnbr = nbr.length();
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, counter);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
counter++;
}
System.out.println();
System.out.println("the sum is: " + sum);
and delete end brackets
The main problem is in your if statement:
if (input == (-input))
That will never be true.
This simplifies your code so it isn't duplicated twice based on a negative/positive number. It could be done better, but I wanted to leave most of your code intact.
System.out.print("enter a number: ");
int input = console.nextInt();
if (input < 0) {
input = input * (-1);
}
String nbr = String.valueOf(input);
int strnbr = nbr.length();
System.out.print("the digits of " + input + " are: ");
int sum = 0;
for (int i = 0; i < strnbr; i++) {
String var = nbr.substring(i, i + 1);
int var1 = Character.getNumericValue(var.charAt(0));
System.out.print(var + " ");
sum = sum + var1;
}
System.out.println();
System.out.println("the sum is: " + sum);
import java.util.Scanner;
import java.util.Random;
public class ResponseTimeProject
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.print("Please enter your full name: ");
String name = in.nextLine();
System.out.println("Hello " + name + ". Please answer as fast as you can." + "\n\nHit <ENTER> when ready for the question.");
in.nextLine();
for (int count = 0; count < 4; count ++) {
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int character=(int)(Math.random()*26);
String s = alphabet.substring(character, character+1);
Random r = new Random();
int i;
for (i = 0; i < 1; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
long startTime = System.currentTimeMillis();
System.out.print("What is the next letter in the alphabet?" + " ");
String response = in.nextLine();
long endTime = System.currentTimeMillis();
String outcome;
if (alphabet.substring(character+1, character+2).equals(response)) {
outcome = "Correct!";
} else {
outcome = "Incorrect.";
}
long reactionTime = endTime - startTime;
System.out.println(outcome);
System.out.println("The average time it took you was " + reactionTime + " milliseconds");
System.out.println("Thank you " + name + ", goodbye.");
}
}
}
HELP:
This code runs but it gives me the wrong answer. I do not know what is wrong. It prints incorrect for the right outcome. Not sure what I need to fix
The code in question is really a total mess (substring to get a character from a String, loops of a single iteration, etc.). But the fundamental issue relating to the question is that the "next letter in the alphabet" depends upon an output that is printed but never stored. It is currently
for (i = 0; i < 1; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
and therefore never saved, so there is nothing to compare it to.
So, save the next character, and then print it.
char nextLetter = alphabet.charAt(r.nextInt(alphabet.length());
Then in the comparison, for the response, check the response against an actual value, not some random substring from the alphabet String.
response = in.nextLine();
char chkChar = response.charAt(0);
if (chkChar == nextLetter) {
...
}
I'm currently working on this assignment for a class and I'm having a hard time getting my while loop to work. Can anyone assist me on figuring out why I can't get the user to enter y or n to either restart the loop or terminate it? Thank you so much!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main (String[] args) {
String another="y";
double percent;
int answers;
int score = 0;
Scanner scan = new Scanner(System.in);
NumberFormat fmt = NumberFormat.getPercentInstance();
// Asks the user to input the amount of questions on the quiz
System.out.print("How many questions are on the quiz? ");
final int QUESTIONS = scan.nextInt();
System.out.println(); // spacer
int[] key = new int [QUESTIONS];
// Asks the user to enter the key
for (int i=0; i<key.length; i++){
System.out.print("Enter the correct answer for question "+ (i+1) +": ");
key[i] = scan.nextInt();
}
System.out.println(); // spacer
while (another.equalsIgnoreCase("y")) {
// Asks the user to enter their answers
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
// Grades the amount of questions right and gives the percentage
percent = (double)score/QUESTIONS;
System.out.println();
System.out.println("Your number of correct answers is: " + score);
System.out.println("Your quiz percentage: " + fmt.format(percent));
System.out.println();
System.out.println("Grade another quiz? (y/n)");
another = scan.nextLine();
}
}
}
So instead of this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
you should try this
for (int i=0; i<key.length; i++) {
System.out.print("Student's answer for question " + (i+1) + ": " );
answers = scan.nextInt();
if (answers == key[i])
score++;
}
scan.nextLine();
At the end of your while loop, try adding this print statement:
System.out.println("Next line is >>>" + another + "<<<");
That should make it clear what you are getting from the scan.nextLine() call. It won't fix your problem, but it will make the issue obvious.
It has to do with that your scan is reading integers before getting the y/n from the user.
In this transition, the scan is reading a newline character instead of y. As a result, the another is a newline char and hence fails the while-loop condition.
To overcome this, the shortcut method is what #3kings had mentioned.
Another method is scan all inputs as string (nextLine) and then for the quiz part, parse for integer. It may seems a lot of work but you get to use parseInt and try/catch exception.