I am coding in Java and I have to create a program that accepts user input, which I have done. But I am confused as to what statement I can use to list those integer input by the user.
This is what I have so far:
//Biker's Journey Program
import java.util.Scanner;
public class lab2
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in);
int w;
int x;
int y;
int z;
int result;
System.out.print("Please enter the first day's traveled miles: ");
w = input.nextInt();
System.out.print("Please enter the second day's traveled miles: ");
x = input.nextInt();
System.out.print("Please enter the third day's traveled miles: ");
y = input.nextInt();
System.out.print("Please enter the last day's traveled miles: ");
z = input.nextInt();
System.out.print("The number of miles traveled was: ");
System.out.println()
result = (w + x + y + z) / 4;
System.out.printf("The average miles per day traveled is %d\n", result);
}
}
And this segment of code does the computing, I just can not figure out how to get the integers listed like this this picture: http://imgur.com/KFNkWEd
System.out.printf("The number of miles traveled each day was: %d %d %d %d", w,x,y,z);
Related
I am trying to write a program to allow the user to input two polynomials with different degrees, I believe that my do while loop is incorrect and I cannot figure out how to let the user input the second polynomial.
{
int i, coef, x, deg;
double total=0.0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Degree");
deg=sc.nextInt();
System.out.println("Enter x");
x=sc.nextInt();
do
{
for (i=0; i<=deg; i++)
{
System.out.println("Enter Coefficent for " +i);
coef=sc.nextInt();
total=total+coef*Math.pow(x,i);
}
}
while ( deg != 0);
When the user selects yes, it loops and starts again. When the user selects N, it should end the program but I am not sure what I am missing here. This is a program to tell you the x and y values when giving the slope and y-intercept to the program.
Java file
int slope;
int yintercept;
String newEquation;
boolean play = true;
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
while (play)
{
if (newEquation.equals("Y"))
{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
}
if (newEquation.equals("N")){
play =false;
}
else{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
}
}
}
}
Why do you have the same code in if (newEquation.equals("Y")) and else part? If you expect user only to enter "Y" or "N", then you can put else in fron, like this:
else if(newEquation.equals("N"))
and delete else part.
Because the way how you wrote it, it tests if input is "Y", and then second time in the same loop iteration it is going to test if input is "N", so that means that your program take the slope info twice once when it goes trough loop, because else refers only to "N".
Try a do-while construct, as well as a equalsIgnoreCase (to make "y" and "Y" both tested against "Y").
int slope;
int yintercept;
String newEquation;
boolean play = true;
do
{
System.out.print("Enter the slope: ");
slope = input.nextInt();
System.out.print("Enter y-intercept: ");
yintercept = input.nextInt();
System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);
System.out.print("\nWould you like to create a new equation... Y or N? ");
newEquation = input.next();
} while newEquation.equalsIgnoreCase("Y")
(I have only cut-and-pasted your lines, but have not compiled and tested. My apologies if I missed something.)
The do-while tests if the user has typed a Y/y after the first round. Note that the user doesn't have to type N/n, but instead could type, say, q in order for the loop to terminate.
I am trying to write a method that will subtract multiple numbers instead of using just 2 input numbers.
So far I have...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
this currently only works with 2 inputs, but my end goal is to be able to continue subtracting multiple numbers.
Instead of continually subtracting from value, instead subtract from difference
Change difference = value - valueTwo; to difference -= valueTwo
This will be equivalent to doing ((A - B) - C) - ..., A being the first input, B the second input, C the third input...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
This should work fine
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
Output:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
This solution doesn't hang after the first input. It is more user friendly.
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
Why have two variables? Anyway, the following is simpler and prompts correctly:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
Test
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0
Read in information for ALL students before doing any calculations or displaying any output. Verify
that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered.
Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid,
display an error message and allow the user to re-enter that invalid score. Once all student info is read
in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s
exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade,
based on the following percentages:
90-100 A, 80-89.9 B, 70-79.9 C, 60-60.9 D, Below 60 F
This is what i have typed out already but its giving me some errors and I'm not sure I'm assigning the values correctly.
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
int [] exams = new int[4];
int student = 1;
do
{
String [] names = new String[student];
System.out.print("PLease enter the name of student" + student );
names[student-1] = s.nextLine();
for ( int i = 1; i < exams.length; i++){
if(i==4){
System.out.print("Please enter score for Final Exam: ");
}
System.out.print("Please enter score for Exam" + i);
exams[i] = s.nextInt();
if((exams[1]<0||exams[1]>50)||(exams[2]<0||exams[2]>50)||(exams[3]<0||exams[3]>50)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[4]<0||exams[4]>100){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
System.out.println("do you wish to enter another?");
again = s.nextLine();
student++;
}while (again.equalsIgnoreCase ("y"));
}
}
This is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Proj4.main(Proj4.java:32)
But its confusing because line 32 is just a } so i really don't know exactly what it means,
i know i probably need to reduce the length of one of the inputs for the arrays but I'm not sure which or if there's even more wrong than that.
EDIT:
Sorry here is my question, Would you guys help me figure out the problem and/or tell me if or what i am doing wrong to get the output required of me?
Array exams has 4 elements only but you try to access 5th element with index 4 here exams[4]<0. First index of array is 0 (not 1).
Does the below work for you?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
int[] exams = new int[4];
int student = 1;
do {
String[] names = new String[student];
System.out.print("PLease enter the name of student" + student);
names[student - 1] = s.nextLine();
for (int i = 0; i < exams.length; i++) {
System.out.println(i + " i");
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
if (exams[3] < 0 || exams[3] > 100) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else {
System.out.print("Please enter score for Exam " + i);
exams[i] = s.nextInt();
if ((exams[i] < 0 || exams[i] > 50)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.println("do you wish to enter another?");
again = s.next();
student++;
} while (again.equalsIgnoreCase("y"));
}
im a beginner in Java, and i have a problem to do:
the problem prompts the user 5 times to enter, the Name of a stock then the Share Price then the number of shares owned and we should calculate the sum of all the stock values, i wrote it using only two prompts using a loop, but my issue is that, in the second prompt time the loop Skips the String input for the second Name of stock instead of promting...bellow is the code:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sharePrice =0,stockPrice = 0, temp = 0 ;
int i = 0;
double sum=0;
String name;
while (i < 2) {
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
stockPrice = sharePrice * (double)(numberOfshares);
sum += stockPrice;
i++;
}
System.out.println("the total stockprice owned is: " + sum );
}
}
And this is the output i get:
Enter the Name of the Stock
nestle
Enter the Share price
2
Enter the number of owned shares
4
Enter the Name of the Stock
Enter the Share price
What makes the input skip during the second loop?
Again as per my comment the problem is that your code doesn't handle the End Of Line (EOL) token when calling nextInt() or nextDouble().
The solution is to use input.nextLine() after getting your int and double in order to swallow the EOL token:
sharePrice = input.nextDouble();
input.nextLine(); // add this
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
input.nextLine(); // add this
stockPrice = sharePrice * (double)(numberOfshares);
The problem is that the last time you call
int numberOfshares = input.nextInt();
in the first iteration of the loop your first passes a carriage return as the next stock name. You could instead use:
double sharePrice = Double.parseDouble(input.nextLine());
and
int numberOfshares = Integer.parseInt(input.nextLine());
You should readout the newline characters after reading the share price and number of shares:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sharePrice = 0, stockPrice = 0;
int i = 0;
double sum = 0;
String name;
while (i < 2)
{
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
// Read out the newline character after the share price.
input.nextLine();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
// Read out the newline character after the number of shares.
input.nextLine();
stockPrice = sharePrice * (double) (numberOfshares);
sum += stockPrice;
System.out.println(String.format("Name: %s, Price: %f, Shares: %d, Total: %f",
name,
sharePrice,
numberOfshares,
stockPrice));
i++;
}
System.out.println("the total stockprice owned is: " + sum);
}
See the lines with comments above: