I'm a beginner to the Java language. Firstly I want use a Scanner to retrieve data
For example, I enter this: 990921205 v
How can I detect the first 2 numbers for any calculation?
How can I detect each numbers for an algorithm?
I tried this:
import java.util.Scanner;
class ID2 {
public static void main(String args[]){
Scanner in=new Scanner (System.in);
int num[]=new int[3];
int A=0;
int B=0;
int C=0;
System.out.println("enter a number " +A);
}
}
With next() method of Scanner you can obtain user standard input.
String userInput = in.next();
int first = Integer.parseInt(userInput.charAt(0));
int second = Integer.parseInt(userInput.charAt(1));
//DO STUFF
Well to get the inputted values you can use Scanner.next(), but if this inputted value is an int you can also use Scanner.nextInt() to read it as an integer:
int value1= in.nextInt();
Then you will have an integer in the value1 value.
But if you are entering a string you will use the Scanner.next()to get this string and then extract the first two elements:
String s=in.next();
int firstTwoval=Integer.parseInt(s.substring(0, 2));
The answer #bigdestroyer gives this error: The method parseInt(String) in the type Integer is not applicable for the arguments (char)
You can just do it with char and not with integers at all.
For example,
Scanner input = new Scanner(System.in);
String numInput = input.next();
char nums[] = new char[numInput.length()];
for (int i = 0;i < numInput.length(); i++){
nums[i] = numInput.charAt(i);
System.out.println("For nums["+i+"] : "+nums[i]);
}
Input:
0123456789
Output:
For nums[0] : 0
For nums[1] : 1
For nums[2] : 2
For nums[3] : 3
For nums[4] : 4
For nums[5] : 5
For nums[6] : 6
For nums[7] : 7
For nums[8] : 8
For nums[9] : 9
Now since you want the first 2,3,4++ digits, you can apply the answer #chsdk gave.
If you use mine you have to parse them to integer using Integer.parseInt() to be sure that it's an actual number.
Related
I want to ask how to convert an int value to string while runing in loop lets say i got an int value 1 at first running of loop then i got 2 and then 3 in the end i want a string with value "123"..
your answers would be very helpful.. THANKS
int sum = 57;
int b = 4;
String denada;
while(sum != 0)
{
int j = sum % b;
sum = sum / b
denada = (""+j);
}
how to convert an int value to string
String.valueOf function returns the string representation of an int value e.g. String x = String.valueOf(2) will store the "2" into x.
lets say i got an int value 1 at first running of loop then i got 2
and then 3 in the end i want a string with value "123"
Your approach is not correct. You need variables for:
Capturing the integer from the user e.g. n in the example given below.
Store the value of the appended result e.g. sum in the example given below.
Capturing the user's choice if he wants to continue e.g. reply in the example given below.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String reply = "Y";
String sum = "";
while (reply.toUpperCase().equals("Y")) {
System.out.print("Enter an integer: ");
int n = Integer.parseInt(scan.nextLine());
sum += n;
System.out.print("More numbers[Y/N]?: ");
reply = scan.nextLine();
}
System.out.println("Appnded numbers: " + sum);
}
}
A sample run
Enter an integer: 1
More numbers[Y/N]?: y
Enter an integer: 2
More numbers[Y/N]?: y
Enter an integer: 3
More numbers[Y/N]?: n
Appnded numbers: 123
The next thing you should try is to handle the exception which may be thrown when the user provides a non-integer input.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
The question is that write a class named Seyyed includes a method named seyyed. I should save the name of some people in a String array in main method and calculate how many names begin with "Seyyed". I wrote the following code. But the output is unexpected. The problem is at line 10 where the sentence "Enter a name : " is printed two times at the first time.
import java.util.Scanner;
public class Seyyed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
}
for example When I enter 3 to add 3 names the program 2 times repeats the sentence "Enter a name : " and the output is something like this:
Enter the number of names :3
Enter a name :
Enter a name :
Seyyed Saber
Enter a name :
Ahmad Ali
There are 1 Seyyed
I can enter 2 names while I expect to enter 3 names.
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Right after in.nextInt(); just add in.nextLine(); to consume the extra \n from your input. This should work.
Original answer: https://stackoverflow.com/a/14452649/7621786
When you enter the number, you also press the Enter key, which does an "\n" input value, which is captured by your first nextLine() method.
To prevent that, you should insert an nextLine() in your code to consume the "\n" character after you read the int value.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
Good answer for the same issue: https://stackoverflow.com/a/7056782/4983264
nextInt() will consume all the characters of the integer but will not touch the end of line character. So when you say nextLine() for the first time in the loop it will read the eol left from the previous scanInt(), so basically reading an empty string. To fix that use a nextLine() before the loop to clear the scanner or use a different scanner for Strings and int.
Try this one:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of names :");
int n = in.nextInt();
in.nextLine();
String[] names = new String[n];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter a name : ");
names[i] = in.nextLine();
}
int s = seyyed(names);
System.out.println("There are " + s + " Seyyed");
in.close();
}
static int seyyed(String[] x) {
int i = 0;
for (String s : x)
if (s.startsWith("Seyyed"))
i++;
return i;
}
I want to read multiple words into a string called input. The words can be casted into numeric values like "1 14 5 9 13". After the user input, the string will be converted into a string array separated by spaces.
public class ArraySum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.next());
System.out.println("Please enter "+n+" numbers");
String input = scanner.next(); // ERROR: only the first word is read
String[] inputs = input.split("\\s+");
int sum=0;
for (int i =0; i<inputs.length; i++){
if (!inputs[i].equals(""))
sum+= Long.parseLong(inputs[i]);
}
System.out.print(sum);
}
}
However only the first word is read into the string.
This answer suggests using nextLine() to read a multi-word string, but if I change it, an error was thrown.
java.lang.NumberFormatException: null
Apparently an empty/null string was inputted before I entered any word.
You have to use nextLine after nextInt to clear your Scanner like this :
int n = scanner.nextInt();//read your int
scanner.nextLine();//clear your Scanner
System.out.println("Please enter " + n + " numbers");
String input = scanner.nextLine();//read your String example 12 55 66
First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!
Ok so i take as an input a list of numbers as a string and i want to take these numbers and create an int array with them.
import java.util.Scanner;
public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;
String s;
Scanner input = new Scanner(System.in);
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = input.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = input.nextInt();
}
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter: ");
s = input.next();
String[] parts = s.split(" ");
System.out.println(parts[1]);
for(int n = 0; n < parts.length; n++) {
System.out.println(parts[n]);
}
input.close();
}
}
Everything would be great if i could get the whole array created printed but for some reason i get this:
Input:
0 0 1 1 2 2
Output:
0
Thats it. Only the 1st element of the array is printed.Should i try to manually print and element such as parts[1](as i do and i get this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at QueueSimulation.main(QueueSimulation.java:32)
Why is this happening? And more importanly how do i fix it?
If you want to read a line, use:
s = input.nextLine();
next() returns the value till the first space.
Read more here