The task is to "Write a program that displays a user-indicated number of multiples for an integer entered by the user."
I suppose I do not need a completely direct answer (although I do want to know the methods/formula to use), as I want to use this as a learning experience in order to do and learn from the task myself. I really want to know about the process and which methods to use, along with finding a formula. :||
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
So far, I have:
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
\\just stuff to base my code off of
int integer;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
\\pretty much everything from here on out.. I'm not sure what to really do.
int n = integer;
int result = (integer * (numberMultiples));
while (result > 0){}
System.out.print(result);
}
} \\at the moment this code doesn't seem to have any running errors
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
NEW QUESTION
I need to loop my program as well. (By asking a question to the user first.) Mines isn't working, as it just keeps looping only the integer loop and doesn't let me type yes/no.
import java.util.Scanner;
public class MultipleLoops
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int integer, numberMultiples;
String repeat = "yes";
while (repeat != "no")
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++){
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
}
}
}
Ok so you need to understand the problem first to know how to solve it
x = First input
n = Second input
you need to calculate n multiple of x
example with x = 3 and n = 10
To calculate 10 multiple of 3 we need to do :
1st multiple = x*1
2nd multiple = x*2
3rd multiple = x*3
...
n multiple = x*n
you can notice that these operations can be replaced by one for loop (notice first and last character of every line, it can be index of your loop )
Back to java :)
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
Replace your code with the following and try this code :
import java.util.Scanner;
public class MultipleLooping{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int integer,numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
}
}
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing multiple N# 1 = 3
Listing multiple N# 2 = 6
Listing multiple N# 3 = 9
Listing multiple N# 4 = 12
Listing multiple N# 5 = 15
Listing multiple N# 6 = 18
Listing multiple N# 7 = 21
Do you want like this ? Below is the code
package com.ge.cbm;
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//just stuff to base my code off of
int integer;
int firstEntered;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
firstEntered = integer;
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
//pretty much everything from here on out.. I'm not sure what to really do.
for (int i=0;i<numberMultiples;i++){
integer=integer*firstEntered;
System.out.println(integer);
}
}
}
Output:
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing the first 7 multiples of 3:
9
27
81
243
729
2187
6561
this should work
while(repeat.equals("yes"))
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++)
{
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
repeat = keyboard.nextLine();
}
Related
I'm having trouble with this array I'm working on. In the for loop, I need to somehow calculate an on base percentage. The element at index 0 will store the OBP. How can I retain the information the user inputs to calculate the OBP? Thank you.
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[index] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[index] = keyboard.nextInt();
}
I'd suggest a HashMap inside a HashMap for this use case.
Before loop:
HashMap<Integer, HashMap<String, Integer>> years = new HashMap<>();
HashMap<String, Integer> entry = new HashMap<>();
For every input from user's keyboard (example):
entry.put("hits", 5);
years.put(2019, entry);
entry.put("walks", 10);
years.put(2019, entry);
In the end you get a result such as:
{2019={hits=5, walks=10}}
Retrieving results is simple too:
// retrieve map of data for a specific year:
years.get(2019)
result: {hits=5, walks=10}
// retrieve specific data for a specific year:
years.get(2019).get("hits")
result: 5
You will want to store the values entered by the user in a variable. Instead of having an array of inputs (which is one way of doing it) - you can simply store each value in a separate variable and then do the calculation at the end.
See my sample code below:
public static void main(String args[]) {
// let's take incoming values from the user for our calculations
Scanner keyboard = new Scanner(System.in);
// we'll use this array to store the values entered by the user
// in position zero of the array we'll store the OBP
// in positions 1-5 we'll store the inputs as entered by the uesr
float[] values = new float[6];
// we'll use this flag to determin if we should ask the user input again or quit the program
boolean letsDoThisAgain = true;
while (letsDoThisAgain){
System.out.println("Enter a Year: ");
int year = keyboard.nextInt();
System.out.println("For Year " + year + ", enter number of:");
System.out.println("Hits: ");
values[1] = keyboard.nextFloat();
System.out.println("Walks: ");
values[2] = keyboard.nextFloat();
System.out.println("Number of times player has been hit by a pitch: ");
values[3] = keyboard.nextFloat();
System.out.println("Number of at bats: " );
values[4] = keyboard.nextFloat();
System.out.println("Number of sacrifice flies: ");
values[5] = keyboard.nextFloat();
// calculate the OBP
values[0] = (values[1] + values[2] + values[3] - values[5] ) / values[4]; // or however you calculate it
System.out.println("OBP: " + values[0]);
System.out.println("------");
System.out.println("Do you want to do it again? (y/n): ");
String quitOrDoItAgain = keyboard.next();
if( "n".equalsIgnoreCase(quitOrDoItAgain)){
letsDoThisAgain = false;
}
}
System.out.println("Thanks for playing... Good Bye!");
}
By the usage of a proper data structure like Map<string year, object playerstats> including OBP calculation on the object player stats before storing but this is an in-memory solution only last till the program is running if you like persistent then look on the database side
Also from the way you have presented your code it seems you are over-writing the value at year[index] always.
if you just want to use an array, then go like
years[index] = year[index] (math operation) keyboard.nextInt()
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);
So I am relatively new to Java language but am trying to get better so I can add more skills to my resume. I am currently focusing on arrays and I am writing a program that I want to be able to use with a barcode scanner or keyboard in order to keep track of Cultural Enrichment credits (inspired by my school's need of one ). I thought it might be a neat starting program to wrap my head around array use but I am having a problem with the two arrays. They keep overwriting the new values entered. I have been googling and trying things but I am still not able to get them to work properly and would like to ask for help from more seasoned coders. I know my output method is rather lazy but it'll do for what I would like to see for the output format.
Here is my code:
public static void main(String []args)throws InputMismatchException
{
Scanner user_input = new Scanner( System.in );
int n = 0;
String Name;
int CEU;
String[] users = new String[5];
String[] numbers = new String[6];
Object end = null;
Object print = null;
System.out.print("Enter value for CEU: ");
CEU = user_input.nextInt();
while (n >= 0)
{
/* Loop*/
System.out.println("Scan ID or type **end,print** ");
numbers[n] = user_input.next();
if ("end".equals(users[n] ))
{
System.out.print("Program terminated.");
System.exit(0);
}
if ("print".equals(numbers[n]))
{
System.out.print("CEUs: " + CEU);
System.out.print(" ID#: " + numbers[0]);
System.out.print(" Name: " + users[0]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[1]);
System.out.print(" Name: " + users[1]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[2]);
System.out.print(" Name: " + users[2]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[3]);
System.out.print(" Name: " + users[3]);
System.out.print("\nCEUs: " + CEU);
System.out.print(" ID#: " + numbers[4]);
System.out.print(" Name: " + users[4]);
}
else
{
System.out.print("Enter Name: ");
users[n] = user_input.next();
}
}
}
Inside your loop you need to increment n as it is always 0. Use: n++; at the last line of code inside the while loop.
n isn't being incremented. Because n never changes, it will override the same part of the array each time the loop executes. Also, it seems like you may get a outofbounds error later, because i will keep increasing. Soon it will be greater than the max index of the numbers array, so it will return the error. You should try adding in some code that stops the error from happening.
So I am trying to write a program that automates making an Operations Order (or OPORD). It is pretty straight forward, but I am having some issues with my arrays, more specifically how to get them to display properly in the output.
Here is my code:
import java.util.*;
import java.util.Scanner;
public class opord {
public static void main(String[] args){
//Variables
int opord_type, phase_a = 0, n = 1, tasks = 0, phase_b = 0, phase_c = 0;
//Strings for paragraph 1
String area_interest = " ", area_ops = " ", enemy_forces = " ", weather = " ", terrain = " ", friendly_forces = " ", civil_consid = " ", attach_detach = " ";
//Strings for paragraph 2
String who = " ", what = " ", where = " ", when = " ", why = " ";
//Strings for paragraph 3
String commander_intent = " ", phases;
Scanner keyboard = new Scanner(System.in);
//Array Lists
ArrayList alist = new ArrayList();
ArrayList blist = new ArrayList();
ArrayList clist = new ArrayList();
//Page One
System.out.println("Welcome to Automated OPORD");
System.out.println("Please choose which type of OPORD you want: (1:Garrison, 2:Tactical)");
opord_type = keyboard.nextInt();
if(opord_type == 1){
//Page Two
System.out.println("Paragraph One: ");
System.out.println("Situation: ");
//Indent One
System.out.println("Enter area of interest: ");
area_interest = keyboard.next();
System.out.println("Enter area of operations: ");
area_ops = keyboard.next();
//Indent Two
System.out.println("Enter weather: ");
weather = keyboard.next();
System.out.println("Enter terrain: ");
terrain = keyboard.next();
//End Indent Two
System.out.println("Enter enemy forces: ");
enemy_forces = keyboard.next();
System.out.println("Enter friendly forces: ");
friendly_forces = keyboard.next();
System.out.println("Enter civil considerations: ");
civil_consid = keyboard.next();
System.out.println("Enter attachments and detachments: ");
attach_detach = keyboard.next();
//End Indent One
//Page Three
System.out.println("Paragraph Two: ");
System.out.println("Mission");
//Indent One
System.out.println("Enter who: ");
who = keyboard.next();
System.out.println("Enter what: ");
what = keyboard.next();
System.out.println("Enter where: ");
where = keyboard.next();
System.out.println("Enter when: ");
when = keyboard.next();
System.out.println("Enter why: ");
why = keyboard.next();
//End Intent One
//Page Four
System.out.println("Paragraph Three: ");
System.out.println("Execution: ");
//Indent One
System.out.println("Enter commander's intent: ");
commander_intent = keyboard.next();
System.out.println("Concept of Operations");
//Indent Two
System.out.println("Enter number of phases: ");
phase_a = keyboard.nextInt();
for (int ph=0; ph<phase_a; ph++) {
System.out.println ("Enter phase " + (ph+1));
alist.add (keyboard.next());
}//End Indent Two
System.out.println("Scheme of Movement and Maneuver");
//Indent Three
System.out.println("Enter number of phases: ");
phase_b = keyboard.nextInt();
for (int p=0; p<phase_b; p++) {
System.out.println ("Enter phase " + (p+1));
blist.add (keyboard.next());
}//End Indent Three
System.out.println("Task to Subordinate Units");
//Indent Four
System.out.println("Enter number of tasks: ");
tasks = keyboard.nextInt();
for (int h=0; h<phase_b; h++) {
System.out.println ("Enter task " + (h+1));
clist.add (keyboard.next());
}
}else if(opord_type == 2){
}
//Output for Garrison
System.out.println("Output for Garrison");
for (int ph=0; ph<phase_a; ph++){
System.out.println("Phase " + n++ + ": " + alist.get(ph));
}
for (int p=0; p<phase_b; p++){
System.out.println("Phase " + n++ + ": " + blist.get(p));
}
for (int h=0; h<phase_c; h++){
System.out.println("Phase " + n++ + ": " + clist.get(h));
}
//Output for Tactical
}
}
I need the output of the phases and the tasks to look like this:
Concept of Operations:
Phase One: Here is some text that the user input
Phase Two: Here is some text that the user input
Phase Three: Here is some text that the user input
Phase (whatever the number the user input): Here is some text that the user input
Scheme of Movement and Maneuver:
Phase One: Here is some text that the user input
Phase Two: Here is some text that the user input
Phase Three: Here is some text that the user input
Phase (whatever the number the user input): Here is some text that the user input
Task to Subordinate Units:
Task One: Here is some text that the user input
Task Two: Here is some text that the user input
Task Three: Here is some text that the user input
Task (whatever the number the user input): Here is some text that the user input
Tactical is mostly mirrored with some changes so don't worry about that, I just need to fix this code so that. I just have to get this code finished, any help would be wonderful!
Thank you!
If I'm understanding you correctly, this is a question about how to create line breaks in the console output of a Java application.
The Character for this is "\n". Put that into print command when you want to do a line break.
//Page Three
System.out.println("\nParagraph Two: ");
System.out.println("Mission");
etc...
Further more, looking at your expected output (I don't know if this is important) but if you want to user input to be next to the text strings, rather than below, use System.out.print (without the ln at the end)
.println will do a line break after finishing the regular print operation
I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.
The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.
Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);
for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}
You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;
Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}