Getting a value from for-loop? - java

i want to get all num values and print in to (......) but i couldnt do that. can u please help me?
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int operands,num;
int q=1;
int a=0;
do
{
System.out.println("Enter the number of operands (in range 2-10):");
operands=keyboard.nextInt();
} while ((operands<2) || (operands>10));
for (int number=1; number<=operands; number++)
{
System.out.println("Enter number "+number+":");
num=keyboard.nextInt();
q=q*num;
}
System.out.print("Multiplication of numbers "+(.......)+" is: "+q);

I like FranzKnut answer but if performance is an issue, and even if it isn't, then please consider using a string builder instead.
Before the loop use
StringBuilder sb = new StringBuilder("my numbers are: ");
Inside the loop add the following code.
sb.append(num);
Then at the end of loop you have something like
System.out.println(sb.toString());

Use an additional String variable you declare before the loop:
String numbers=" ";
and add to it in the loop body:
numbers += num+" ";
then print out this string in the place of (.......)

Simply add a String into the program and concat with the new added numbers. Finally print string where you have to print.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int operands, num;
int q = 1;
int a = 0;
String s = " ";
do {
System.out.println("Enter the number of operands (in range 2-10):");
operands = keyboard.nextInt();
} while ((operands < 2) || (operands > 10));
for (int number = 0; number <= operands - 1; number++) {
System.out.println("Enter number " + number + ":");
num = keyboard.nextInt();
s = s + num;
q = q * num;
}
System.out.print("Multiplication of" + s + " numbers is: " + q);
}

ok here you got
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
int operands,num;
int q=1;
int a=0;
List<Integer> numbers = new ArrayList<Integer>();
int newNumbers = 1;
do
{
System.out.println("Enter the number of operands (in range 2-10):");
operands=keyboard.nextInt();
} while ((operands<2) || (operands>10));
for (int number=1; number<=operands; number++)
{
System.out.println("Enter number "+number+":");
num=keyboard.nextInt();
q=q*num;
numbers.add(num);
}
StringBuilder newTextNumber = new StringBuilder("");
for(Integer s: numbers){
newTextNumber.append(s).append(" ");
newNumbers *= s;
}
System.out.print("Multiplication of numbers "+newTextNumber+" is: "+newNumbers);
}
}
Enter the number of operands (in range 2-10):
3
Enter number 1:
20
Enter number 2:
30
Enter number 3:
10
Multiplication of numbers 20 30 10 is: 6000

Related

I was writing a code to enter a number and then reversing it, but the modulo isn't working it seems. What could have gone wrong here?

My concern is only with why the modulo (%) isn't working. Please don't comment on the code on it's entirety. My code is as displayed below.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Enter a number");
int num = scanner.nextInt();
int count = 0;
while(num!=0) {
num = num/10;
count++;
}
System.out.println("Total digits = " + count );
int rem = num % 10;
System.out.println(rem);
}}
The output is
Also quick note: the output for "rem" is 0 only when "num" is passed as an operand. If a number replaces the "num" then the code works just fine
There is a wrong logic used for reversing the number. You can try below code.
public class ReverseNumberExample1
{
public static void main(String[] args)
{
int number = 987654, reverse = 0;
while(number != 0)
{
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10;
}
System.out.println("The reverse of the given number is: " + reverse);
}
}

Using a for loop, display the number of entries and the sum in Java

so I was asked to create a program in which the user enters four integers and then displays the number of entries and the sum of the integers using a for loop. This is what I came up with.
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
for (int i = 0; i != 4 ; i++)
{
System.out.println(" Enter an integer: ");
int num = in.nextInt();
sum = sum + num;
count = count + 1;
}
System.out.println("Number of entries: " + count);
System.out.println("Total sum of entries: " + sum);
}
}
I was wondering what a cleaner way was to ask the user for the four numbers using a for loop, and what other people might suggest be best for this situation. Thanks for any input, p.s. (I have just started learning!)
i think you are looking something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum=0;
for(int i=0;i<4;i++){
System.out.println("ENter Number"+(i+1));
sum += sc.nextInt();
}
System.out.println("the Sum is "+sum);
sc.close();
}
You can check with enter. If user presses enter, you can break.
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
break;
}
Have a look at this solution. I cleaned it up a bit. Maybe you will find some design decisions I made which will help you in the future:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
for (int count = 1; count <= 4; count++) {
System.out.print(String.format("Please enter %d. integer: ", count));
sum = sum + readNumber(scanner);
}
System.out.println("The sum of numbers entered is: " + sum);
}
}
private static int readNumber(Scanner scanner) {
do {
String input = scanner.nextLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.print(String.format("Input %s is not a valid integer. Try again: ", input));
}
} while (true);
}
As you're a beginner it's the best way for getting input from the user in console. But you are for the condition should be like:
for ( int i =0;i < 4 ; i ++){}

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

Create a java program that prompt the user for a positive number and then displays each digit in reverse order on a separate line

import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
output:
Please enter a value:
789
7
8
9
How do I reverse the output? For example, when I enter the number 123, it would display 321 with each digit on a new line.
If the user is inputting values in base 10, you could instead use the modulo operator along with integer division to grab the rightmost values successively in a while loop as so:
import java.util.Scanner;
public class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int quotient = value;
int remainder = 0;
while(quotient != 0){
remainder = quotient%10;
quotient = quotient/10;
System.out.print(remainder);
}
}
}
This might be a better method that attempting to convert the int to a string and then looping through the string character by character.
Loop you printing for loop in the reverse direction:
import java.util.Scanner;
class Digitsdisplay {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = digit.length()-1; i >= 0; i--) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Edit: No reason to reverse the string itself, ie. using a Stringbuilder like the other answers say. This just adds to the runtime.
import java.util.*;
public class Francis {
public static void main(String[] args) {
Scanner input= new Scanner (System.in);
System.out.println("Please enter a value: ");
int value = input.nextInt();
int total = 0;
String digit = "" + value;
System.out.print("");
for (int i = 0; i < digit.length(); i++) {
int myInt = Integer.parseInt(digit.substring(i, i + 1));
System.out.println(myInt);
total += myInt;
}
}
}
Simply reverse the string before looping through it
digit = new StringBuilder(digit).reverse().toString();

How to change string into integer and add them?

Im writing a code that will will take the entered number and only add the values that are in the even positions.
For example:
If user enters 53429
The sum of of the even positions is 5.
My issue is I'm trying to convert the strings of the even positions back into integers and add them together. This is what I have
I keep receiving an error when I try to parse the string to an integer.
Cannot find symbol
symbol : method parseInt(java.lang.String)
location: class Integer
Code:
import java.util.Scanner;
public class NumberSums {
public static void main(String [] args) {
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if (length<5) {
System.out.println("Invalid value");
System.exit(0);
}
if (length>5) {
System.out.println("Invalid value");
System.exit(0);
}
String s2 = s1.substring(0,1);
String s3 = s1.substring(1,2);
String s4 = s1.substring(2,3);
String s5 = s1.substring(3,4);
String s6 = s1.substring(4,5);
int a = Integer.parseInt(s3);
//int b = Integer.parseInt(s5);
//sum = (a + b);
System.out.println("The sum of all even positions is " + sum);
}
}
I'm willing to bet that you have a class named Integer, and Java is trying to use that rather than java.lang.Integer.
Rename your class, or use java.lang.Integer.parseInt(s3) instead.
code to add even placed chars in the string.
String str="1234567";
int sum=0;
for(int i=1;i<str.length();i=i+2){
sum+=(str.charAt(i)-'0');
}
System.out.println(sum);
And we can also take from keyboard and start the calculation:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter number : ");
String number=null;
try{
number = reader.readLine();
}
catch (IOException e) {
e.printStackTrace();
throw e;
}
int sum=0;
for(int i=1;i<number.length();i=i+2){
sum+=(number.charAt(i)-'0');
}
System.out.println(sum);
I ran the program and it works fine... if you uncomment the lines int b and sum = (a + b);. However, you have to declare the sum variable, i.e. int sum = (a + b);
What JDK are you running? The error you describe would only occur if Integer.parseInt(String foo); didn't exist, except it's been around since at least Java 1.4, so I'm not sure why you wouldn't find it; unless you have another Integer class defined in the same package, which could confuse the compiler.
Here is the complete program, including imports (which may be the problem, if you're importing a different Integer than java.lang.Integer), fixing the variable declaration and removing unnecessary code, fixing indentation, and adding a Scanner.close() statement:
import java.util.Scanner;
public class Test {
public static void main(String [] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if(length != 5)
{
System.out.println("Invalid value");
System.exit(0);
}
String s3 = s1.substring(1,2);
String s5 = s1.substring(3,4);
int a = Integer.parseInt(s3);
int b = Integer.parseInt(s5);
int sum = (a + b);
System.out.println("The sum of all even positions is " + sum);
keyboard.close();
}
}
The Modified code. Try understanding it.
import java.util.Scanner;
public class EvenPos {
public static void main(String [] args)
{
Scanner keyboard=new Scanner(System.in);
System.out.print("Enter a number: ");
String x=keyboard.next();
String s1 = x;
int length = s1.length();
if(length<5) {
System.out.println("Invalid value");
System.exit(0);
}
if(length>5) {
System.out.println("Invalid value");
System.exit(0);
}
else{
char a = s1.charAt(1);
char b = s1.charAt(3);
int q = Character.getNumericValue(a); //Convert Char to Integer
int z = Character.getNumericValue(b); // //Convert Char to Integer
int sum = 0;
if (q % 2 == 0 && z % 2 == 0){ //If both even, then.....
sum = q+z;
System.out.println("Your sum: " + sum);
}
else{
System.out.println("No even Number found at even POS");
}
}
}
}

Categories

Resources