I am very new to java. I am trying to prompt the user to enter 4 integer numbers followed by a space and eventually print them out at the end. I am a little confused with the order of how I write things out and using the split(" ");
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
int numbers = keyboard.nextInt();
// Need split(" "); here?
} // End main string args here
} // End class calculations here
Any help or advice is appreciated. I have looked at other ways on stackoverflow but somehow I keep getting errors.
Read it in one String with keyboard.nextLine
Use the split method of String for get an array of Strings
Convert every element of the array to int with Integer.parseInt
Print your ints.
import java.util.Scanner;
public class calculations {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter 4 integer numbers here: ");
// Scan an entire line (containg 4 integers separated by spaces):
String lineWithNumbers = Keyboard.nextLine();
// Split the String by the spaces so that you get an array of size 4 with
// the numbers (in a String).
String[] numbers = lineWithNumbers.split(" ");
// For each String in the array, print them to the screen.
for(String numberString : numbers) {
System.out.println(numberString);
}
} // End main string args here
} // End class calculations here
This code will print all numbers, in case you actually want to do something with the Integers (for example mathematical operations) you can parse the String to an int, like so:
int myNumber = Integer.parseInt(numberString);
Hope this helps.
If would suggest to use the abilities of the Scanner class to retrieve numbers from the user input:
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[4];
System.out.println("Enter 4 integer numbers here: ");
for (int i = 0; i < 4 && keyboard.hasNextInt(); i++) {
numbers[i] = keyboard.nextInt();
}
System.out.println(Arrays.toString(numbers));
This code creates an array of size 4 and then loops over the user input reading the numbers from it. It will stop parsing the input if he has the four numbers, or if the user enters something different than a number. For example, if he enters 1 blub 3 4, then the array will be [1, 0, 0, 0].
This code has some advantages compared to the nextLine approaches of the over answers:
you don't have to care about the integer conversion (exception handling)
you can either write these number onto one line or each number on its own line
If you like to read an arbitrary amount of numbers, then use a List instead:
List<Integer> numbers = new ArrayList<>();
System.out.println("Enter some integer numbers here (enter something else than a number to stop): ");
while (keyboard.hasNextInt()) {
numbers.add(keyboard.nextInt());
}
System.out.println(numbers);
Related
I'm new in this, i'm trying to write a code which stores user input in a array of n length (the length is also decided by the user).
So I decided to use a while loop to use Scanner n times, so that each time the user could store an String in that location as the loop advances.
But when I run the code, it just prints the statements don't letting me (or the user) to input the String.
public static void main(String[] args) {
String[] contadores;
Scanner cont= new Scanner(System.in);
System.out.println("Input the length of the array + 1: ");
int cuenta = cont.nextInt();
// Thread.sleep(4000);
contadores = new String[cuenta];
Scanner d = new Scanner(System.in);
int i=0;
while (i<= (contadores.length-1)) {
System.out.println("Input the word in the space: "+(i));
String libro = d.toString();
contadores[i] = libro;
i++;
}
When I run it, the output is:
Input the length of the array + 1:
3
Input the word in the space: 0
Input the word in the space: 1
Input the word in the space: 2
As you see it doesn't give me enough time to input something, I don't know if it JDK (I think not), or it is because is inside the main, I tried using Thread.sleep(4000); but the output is an error Unhandled exception type InterruptedException.
The problem is that you are not scanning inside the while loop. You need to scan the words the way you have scanned the integer. Instead of using d.next(), you've used d.toString().
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] contadores;
Scanner cont = new Scanner(System.in);
System.out.print("Input the length of the array: ");
int cuenta = cont.nextInt();
contadores = new String[cuenta];
int i = 0;
while (i < contadores.length) {
System.out.print("Input the word for the index " + (i) + ": ");
String libro = cont.next();
contadores[i] = libro;
i++;
}
// Display the array
for (String s : contadores) {
System.out.println(s);
}
}
}
A sample run:
Input the length of the array: 4
Input the word for the index 0: Hello
Input the word for the index 1: World
Input the word for the index 2: Good
Input the word for the index 3: Morning
Hello
World
Good
Morning
Also, note that I've used only one instance of Scanner. You do not need two instances of Scanner. You can reuse the same instance of Scanner everywhere in your program.
i have a project wherein i have to create multiple classes that form the image of each (ex: Digit0, Digit1,...,Digit9) with a small and a large size. there are 10 different classes so i'll just simplify to what's important. (for example class Digit1 contains a print function that outputs a small number 1 or a big number 1). i have no problem creating the classes for these digits, where i'm stuck is in figuring out the tester program.
the tester program should allow the user to input a number (ex: 1, 25, 4354435454 etc.) and input a size (1 for small, and 2 for large) and print out the desired images. so far i have this code and it works but it only allows single digit numbers
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int digits = scan.nextInt();
int segmentSize = scan.nextInt();
while ((digits!=0)&&(segmentSize!=0)) //terminates when 0 0 is input
{
if (digits==0)
{
if (segmentSize==1) //this is the small size
{
Digit0 small = new Digit0(1);
//this references the small sized 0 created as a method in class Digit0
System.out.println(small.toString());
//this prints the small digit 0
}
else //this is the large size
{
Digit0 big = new Digit0(2);
System.out.println(big.toString());
}
}
//...the other digits are placed as else ifs
}
}
}
i tried altering the scanner objects so that it takes in String digits instead of int digits. so that i could simply split it and use a for loop to go through each character of the string, but i can't seem to get it to work. i really hope i made sense here. i'm a beginner and would really appreciate the help
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
String digits = scan.next(); //takes in a string of numbers
digits.split(" "); //splits the string into its digits
//int segmentSize = scan.nextInt(); commenting this out because it works. just need to focus on the
digits themselves
while ((!digits.equals("0")) && (segmentSize!=0)) //terminates when input is 0 0
{
for (int i=0; i<digits.length(); i++) //goes through all digits of string
{
int num = digits.charAt(i);
switch (num)
{
case 0:
System.out.println("zero"); //there is a longer code referencing the two sizes but the sizes work but i simplified it again. this is just for me to know whether it is printing the right thing
break;
default:
System.out.println("other"); //these are the other digits, but i just condensed them together just to see if its printing right
break;
}
}
digits = scan.next();
digits.split(" ");
//segmentSize = scan.nextInt();
}
}
}
when i input 002, i want to ouput:
zero
zero
other
but instead, it just outputs "other" for all three.
Looking at the question, I think this is what you're looking for:
Scanner scan = new Scanner (System.in);
String digits = scan.nextLine(); //takes in a string of numbers.
int[] digits_split = new int[0]; //creates an int array to store split digits.
digits_split = digits.split(" "); //splits the string into the digits_split array.
By creating an int array it's now easier to validate the digits.
now you can use this loop to check your split digits:
note below is Pseudo Code and has not been tested...
for(int i = 1; i <= digits.length; i++)
{
if(digits_split[i]=0)
{
System.out.println("zero");
}
else
{
System.out.println("other");
}
}
Also ensure that when entering your digits you put a space in between each one so when the program requests for digits you type: 0 0 2
EDIT:
If your digits contain commas use:
digits = digits.replace(",","");
Also once you've split the string use trim:
digits = digits.trim();
It tidy's things up a little.
ALSO:
when i input 002, i want to ouput:
You need to input: (0[space]0[space]2) to get the output you want. As you're splitting on a " ". Otherwise use a symbol.
Hope this helps,
Rob.
How can I make it so that I can prompt the user to input multiple integers on one line that are seperated by spaces. And if the first integer is 0 or less than 0 it will print out "Bad Input" when all the integers are inputted and the user presses enter. Also how can I make it so that when the user enters a negative number at the end of the line, it will stop entering numbers and make multiply all of them together.
This is what I have so far but i'm not sure I am doing this right.
import java.util.Scanner;
public class tempprime {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int count = 1;
String inputnumbers;
System.out.print("Enter integers: ");
inputnumbers = input.nextLine();
for (int i = 0; i < inputnumbers.length(); i++){
if (inputnumbers.charAt(i) == ' ')
count++;
}
int[] numbers = new int[count];
}
}
You already have it so the user can enter in values until they hit enter. Now you can do is use a split operation to break the string up into an array of values.
String[] values = inputnumbers.split('\s');
Then you could replace charAt with access to the array.
Alternatively, Scanner already allows the user to enter in as many integers as they need on the same line. nextLine() finds the first occurance of a new line, but you can use input.nextInt(), grabs the next int stopping at a space, multiple times and read them in one at a time. You can also check if there are any more values remaining using the scanners hasNext methods.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can see an example of reading multiple ints below. The user can enter them in one at a time, or 3 at a time and should still work the same.
Scanner in = new Scanner(System.in);
System.out.print("Enter 3 ints:");
int a,b,c;
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
System.out.printf("A: %d B: %d C: %d", a, b ,c);
How do I input an array whose length may vary? The input is space delimited and ends when I press enter
public class ArrayInput {
public static void main(String args[]){
ArrayList<Integer> al = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(){//what condition to use here?
al.add(sc.nextInt());
}
}
}
An example would be:
1 2 5 9 7 4 //press enter here to mark end of input
Since all your input is in a single line, you can read the entire line and then split it to integers :
String line = sc.nextLine();
String[] tokens = line.split(" ");
int[] numbers = new int[tokens.length];
for (int i=0; i<numbers.length;i++)
numbers[i] = Integer.parseInt(tokens[i]);
Read the entire line using sc.nextLine() and then split() using \\s+. This way, you don't have to worry about size of input (number of elements). Use Integer.parseInt() to parse Strings as integers.
This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
In the following two code snippets, I first ask for the number of inputs required and let the user input that many inputs of a particular kind. When the required inputs are String types, it takes one less input unless I use s.next() first, while for Integers it works fine. I don't understand why. Can someone please explain?. Thanks
First Code with String inputs and nextLine function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
String[] inputs = new String[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextLine();
}
System.out.println("end of code");
}
Second Code with Integer inputs and nextInt function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
Integer[] inputs = new Integer[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextInt();
}
System.out.println("end of code");
}
It is because of the following line:
int num = s.nextInt();
Your next INT only returns the INT until it gets to the \n character.
If you had a test file like this:
4
1
2
3
4
Your character code will look like this:
4'\n'
1'\n'
2'\n'
3'\n'
4'\n'
So when you grab the integer, it will grab the 4 for your "nextInt()" method on the scanner. When you tell it to grab the next line "nextLine()", it will grab the remainder of that line which is just '\n' and store nothing into the first value into your array.
On the reverse side, if you tell it to grab the next integer "nextInt()", it will search until it finds the next integer, which will cause the 1 to go into the first value into the array.