This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
Sample input : 3456
Sample output :
Digits : 3, 4, 5, 6
Sum : 18
This is the code that I had try, but unfortunately it is wrong since i do not use loop.Please anybody can help me?
import java.util.Scanner;
public class Lab1_5 {
public static void main (String args[])
{
int insert1, insert2, insert3, insert4;
int sum ;
Scanner console = new Scanner(System.in);
System.out.print("Please enter First Number: ");
insert1 =console.nextInt();
System.out.print("Please enter Second Number: ");
insert2 =console.nextInt();
System.out.print("Please enter Third Number: ");
insert3 =console.nextInt();
System.out.print("Please enter Fourth Number: ");
insert4 =console.nextInt();
System.out.println("Digits: "+ insert1+","+insert2+","+insert3+","+insert4);
sum = insert1+insert2+insert3+insert4;
System.out.print("Sum: "+ sum);
}
}
You can use a for loop as seen in this example:
public static void main(String args[]){
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Number: ");
//get number input:
int num = sc.nextInt();
//convert number to String:
String str = Integer.toString(num);
//iterate through each char in string:
for(int i = 0; i < str.length(); i++){
//convert char value to int, and add it to the sum:
sum += Character.getNumericValue(str.charAt(i));
}
}
Here's how you can get the sum with a loop:
What this does is it gets one number from the user and loops trough the individual digits of the number.
public static void main(String[] args)
{
int sum = 0;
Scanner console = new Scanner(System.in);
System.out.print("Please enter a Number: ");
String num = console.nextLine();
try
{
num = num.trim();
int index = 0;
int n = Integer.parseInt(num);
System.out.print("Digits: ");
while (n > 0)
{
int digit = n % 10;
sum += n % 10;
n = n /10;
char d = num.charAt(index++);
System.out.print(d + ", ");
}
System.out.print("Sum: " + sum);
}
catch (NumberFormatException e)
{
System.out.print("Invalid Number entered");
}
// Close the scanner
console.close();
}
Here is another version that won't give you an integer overflow for input values over Integer.MAX_VALUE.
public static void main(String[] args)
{
int sum = 0;
Scanner console = new Scanner(System.in);
System.out.print("Please enter a Number: ");
String num = console.nextLine();
try
{
num = num.trim();
System.out.print("Digits: ");
for (int i = 0; i < num.length(); i++)
{
char d = num.charAt(i);
int n = Integer.parseInt(String.valueOf(d));
sum += n;
System.out.print(d + ", ");
}
System.out.print("Sum: " + sum);
}
catch (NumberFormatException e)
{
System.out.print("Invalid Number entered");
}
console.close();
}
public class Lab1_5 {
public static void main (String args[])
{
int insert;
int sum ;
int[] numArray = new int[4];
Scanner console = new Scanner(System.in);
for(int i=0; int<4; i++){
if(i == 1) {
System.out.println("Please enter First Number: ");
} else {
System.out.println("Please enter the next Number: ");
}
numArray[i] = console.nextInt();
sum += numArray[i];
}
System.out.println("Digits: "+ numArray[0]+","+numArray[1]+","+numArray[2]+","+numArray[3]);
System.out.println("Sum: "+ sum);
}
}
Related
I am trying to find all permutations of a pin number coming from a scanner. I have got this bit so far which I guess sets an array with custom digits. How can I get this code to show me all the possible options? Bare in mind that I am new to Java so simple explanations would be the best. Thanks
import java.util.Arrays;
import java.util.Scanner;
public class Methods {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[3];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter first digit: ");
arr[0] = sc.nextInt();
System.out.println("Please enter second digit: ");
arr[1] = sc.nextInt();
System.out.println("Please enter third digit: ");
arr[2] = sc.nextInt();
System.out.println("Please enter fourth digit: ");
arr[3] = sc.nextInt();
System.out.println(Arrays.toString(arr));
}
}
Hey you can use the following code to create an array of n length and calculate the permutations:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("please enter the length of you array: "); // 4 if you want a 4 digit pincode
int length = sc.nextInt();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
System.out.printf("Please enter a value for digit #%s: ", i);
arr[i] = sc.nextInt();
}
StringBuilder bldr = new StringBuilder();
Arrays.stream(arr).forEach(bldr::append);
permutation(bldr.toString());
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
Also check this question for more info about permutations.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 4 years ago.
I have an array of strings - name[]. When I try to take an input from the user using the Scanner class the program seems to ignore the statement and go on to the next.
import java.util.Scanner;
class Student { //start of class
public static void main(String[] args) { //start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i]; //calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
} //end of method main
} //end of class
That's because the sc.nextInt() method does not read the newline character in your input and so you need to call sc.nextLine()
From the docs
Advances this scanner past the current line and returns the input that
was skipped.
This method returns the rest of the current line, excluding any line
separator at the end. The position is set to the beginning of the next
line.
Since this method continues to search through the input looking for
a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
You code will now look like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // <----- observe this
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
sc.nextLine(); // <----- observe this
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i];
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}
Try this.. Your sc.nextLine() is reading empty String after you input integer value
import java.util.Scanner;
class Student
{//start of class
public static void main(String[] args)
{//start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String emp = sc.nextLine();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i=0;i<n;i++)
{
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
emp = sc.nextLine();
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + totalmarks[i];//calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++)
{
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}//end of method main
}//end of class
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and when you are finished enter '=' ");
System.out.print("Enter the first number: ");
ArrayList<String> my_list = new ArrayList<String>();
String value = scanner.next();
int num = Integer.parseInt(value);
if (num == Integer.parseInt(value)) {
my_list.add(value);
} else {
System.out.print("Please enter a number");
}
while (!value.equals("=")) {
System.out.print("Enter a number: ");
value = scanner.next();
my_list.add(value);
my_list.remove("=");
}
System.out.println("The list looks like: ");
System.out.println(my_list);
backarryToNum(my_list);
}
public static void reverseArrayToNum(ArrayList number){
int num;
int sum = 0;
for (int i = number.size()-1; i >= 0 ; i--) {
int n = number.get(i);
num = n * (int)Math.pow(10,i);
sum += num;
System.out.println(sum);
}
}
}
The "int n = number.get(i)" line is the problem.
The method reverseArrayToNum will make the array reverse and will make the reversed array of numbers covert to a number.
Just change
int n = number.get(i);
to
int n = Integer.parseInt((String) number.get(i));
otherwise you try to store a String into an int.
Also, I suppose
backarryToNum(my_list);
is supposed to be
reverseArrayToNum(my_list);
I have a program here in java that asks the user to input ten integer numbers and would print out how many are ODD and how many are EVEN.
import java.io.*;
public class Count {
public static void main(String[] args) {
int i, , even_ctr=0, odd_ctr = 0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++; //counter for even
if(n % 2 == 0)
odd_ctr++; //counter for odd
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ odd_ctr);
}
}
I am trying to change the program by using only one counter instead of two counter. Anyone knows how?
import java.io.*;
public class NewClass {
public static void main(String[] args) {
int i,n, even_ctr=0;
String input = " ";
BufferedReader in = new BufferedReader ( new InputStreamReader(System.in));
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.readLine();
}catch(IOException e){
System.out.println("Error!");
}
n = Integer.parseInt(input);
if(n % 2 == 0)
even_ctr++;
}System.out.println("EVEN: " + even_ctr + "\nODD: "+ (10-even_ctr));
}
}
Just keep the first counter incrementing for ODD number detection (OR EVEN but either of them). At the end of the computation, if ODD counter = 4, and total number of numbers entered are 10, then 10 - ODDcounter = 10 - 4 = 6 are the number of even numbers.
For this it looks like it would be equally useful to use the Scanner so that you can avoid the step of having to parse the string.This also would require you to import java.util.Scanner but you can use the scanner to take in strings or integers.
Scanner in = new Scanner(System.in);
int input;
int evenCount = 0;
for(i = 1; i <=10; i++){
try{
System.out.print("Input integer number: ");
input = in.nextInt();
}catch(IOException e){
System.out.println("Error!");
}
if(input % 2 == 0)
evenCount++;
}
System.out.println("EVEN: " + evenCounter + "\nODD: "+ (10 - evenCounter);
Include in.close(); at the end of the method to close the scanner or the reader which ever you use.
package evenoddten;
import java.util.Scanner;
public class EvenOddTen {
public static void main(String[] args) {
int num1 = 0, num2, even = 0, count = 0;
Scanner scr = new Scanner(System.in);
System.out.print("Total Nos:");
num2 = scr.nextInt();
while(count<num2) {
System.out.println("Enter no:");
num1 = scr.nextInt();
if (num1%2 == 0) {
even = even + 1;
}
count = count+1;
}
System.out.println("Even nos are:"+even);
System.out.println("Odd nos are:"+(count - even));
}
}
Trying to figure out how I would take any amount of inputted numbers from a user and add them together
Example user input: 1 2 3 4
Sum = 10
The user can put any amount of numbers in not a specified amount so if he wanted to add 1 2 3 4 5 6 7 8 9 10 11 12 13, it would sum them all up to 91
Thanks for the help in advance.
import java.util.Scanner;
public class test
{
public static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
while (score >= 0) {
if (score <= -1) {
score = kb.nextInt();
sum += score;
score = 0;
}
System.out.println(sum);
}
}
}
Thanks to libik for all his time and help, here is the finished code.
import java.util.Scanner;
public class JavaApplication1156 {
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
if (sum <= -1)
System.out.println("Application ended");
else if (sum >= 0)
System.out.println("Sum = " + sum);
} while (sum != -1);
}
}
It is very easy actually
import java.util.Scanner;
public class JavaApplication115 {
public static void main(String[] args) {
System.out.println("write numbers, if you write zero, program ends");
Scanner input = new Scanner(System.in); //just copy-and paste this line, you dont have to understand it yet.
int number;
int sum = 0;
do {
number = input.nextInt(); //this reads number from input and store its value in variable number
sum+= number; //here you add number to the total sum
} while(number != 0); //just repeat cycle as long as number is not zero
System.out.println("Sum is : " + sum);
}
}
Working code based on your code :
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println(sum);
}
Also if you are interested in "minimal" version, which is the same as the one before, but using as less code as possible, here it is :
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter numbers here");
Scanner kb = new Scanner((new Scanner(System.in)).nextLine()); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
sum += kb.nextInt();
}
System.out.println(sum);
}
Find sum of each line as long as sum is not zero (based on second block of code) :
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println("Sum = " + sum);
} while (sum != 0);
}
//Input the number in a single line (but be in size limit of integer)
import java.util.Scanner;
public class Sum_of_integers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while(num >= 1) { //base value
int lastval = num % 10; //the logic
num = num / 10;
sum += lastval;
}
System.out.println(sum);
}
}
Question - Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.
Scanner sc = new Scanner(System.in);
int input = 0;
int sum = 0;
while (true){
sum = sum+input;
if (input==5){
System.out.println("Loop is stopped");
System.out.println("The sum is " + sum);
break;
}
else {
System.out.println("Take the inputs");
input = sc.nextInt();
}
}