Is there an equivalent method to C's scanf in Java? - java

Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversion.
I was wondering if there's an input conversion method akin to C's scanf in Java?

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.
Following code is taken from cited website:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
System.out.println("Enter something here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
--
import java.util.Scanner;
public class ReadConsoleScanner {
public static void main(String[] args) {
System.out.println("Enter something here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
}
Regards.

There is not a pure scanf replacement in standard Java, but you could use a java.util.Scanner for the same problems you would use scanf to solve.

Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:
71 5796 2489
88 1136 5298
42 420 842
Here's the code using findAll:
new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
.forEach(result -> {
int fst = Integer.parseInt(result.group(1));
int snd = Integer.parseInt(result.group(2));
int third = Integer.parseInt(result.group(3));
int sum = fst + snd + third;
System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
});

If one really wanted to they could make there own version of scanf() like so:
import java.util.ArrayList;
import java.util.Scanner;
public class Testies {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
// get input
System.out.println("Give me input:");
scanf(strings, nums);
System.out.println("Ints gathered:");
// print numbers scanned in
for(Integer num : nums){
System.out.print(num + " ");
}
System.out.println("\nStrings gathered:");
// print strings scanned in
for(String str : strings){
System.out.print(str + " ");
}
System.out.println("\nData:");
for(int i=0; i<strings.size(); i++){
System.out.println(nums.get(i) + " " + strings.get(i));
}
}
// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
Scanner getLine = new Scanner(System.in);
Scanner input = new Scanner(getLine.nextLine());
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
Scanner input = (new Scanner(in));
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
}
Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.
Output:
Give me input:
apples 8 9 pears oranges 5
Ints gathered:
8 9 5
Strings gathered:
apples pears oranges
Data:
8 apples
9 pears
5 oranges
Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.

C/C++ has a notion of variable references, which makes creating something like scanf much easier. However, in Java, everything is passed by value. In the case of objects, their references are passed by value.
So, it's essentially impossible to have a concise equivalent to scanf. However, you can use java.util.Scanner, which does things similar to scanf.
So this C/C++:
int a;
float b;
scanf("%d %f", &a, &b);
is (roughly) equivalent to this Java:
int a;
float b;
try (Scanner sc = new Scanner(System.in)) {
a = sc.nextInt();
b = sc.nextFloat();
}

Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.
Use Integer.parseInt() to convert your string into Interger.
To print any string you can use System.out.println()
Example :
int a;
a = Integer.parseInt(args[0]);
and for Standard Input you can use codes like
StdIn.readInt();
StdIn.readString();

THERE'S an even simpler answer
import java.io.BufferedReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String myBeautifulScanf = new Scanner(System.in).nextLine();
System.out.println( myBeautifulScanf );
}
}

Related

How to make output in reverse order using Java language?

I am facing a problem taking all the lines from standard input and write them to standard output in reverse order.
That is output each line in the reverse order of input.
Below is my code:
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by
\"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
append += input + " ";
}
sc.close();
System.out.println("The current append: " + append);
String stringArray[] = append.split(" strings" + "");
System.out.println("\n\nThe reverse order is:\n");
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
}
}
When I run my code with sample inputs like below:
Type some text with line breaks, end by "-1":
My name is John.
David is my best friend.
James also is my best friend.
-1
I get the following output:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
My name is John. David is my best friend. James also is my best friend.
Whereas, the required output is something like below:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
James also is my best friend.
David is my best friend.
My name is John.
Can anyone help me to check what is wrong with my code and fix it?
Try the below Code.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by\"-1\":");
List<String> list= new LinkedList<String>();
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
list.add(input);
}
sc.close();
System.out.println("The current append: " + append);
Collections.reverse(list);
for (String string : list) {
System.out.println(string);
}
}
}
Hope This will help you
Instead of appending the input to the append string you should add the input string to a List and then print it from the bottom or use the Collections.reverse() method and then print it straight
Edit - basically same implementation as previous answers, though uses a for loop:
import java.util.ArrayList;
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//create arraylist for lines
ArrayList<String> lines = new ArrayList<String>();
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by \"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
lines.add(input);
}
sc.close();
System.out.println("The current append: ");
for(String line : lines){
System.out.print(line + ". ");
}
System.out.println("\n\nThe reverse order is:\n");
for (int i = lines.size()-1; i >=0 ; i--) {
System.out.println(lines.get(i));
}
}
}
1 - 1 way to do it is run loop from backword.
for (int i = stringArray.length; i >=0 ; i++) {
System.out.println(stringArray[i]);
}
2 - Use Collections.reverse() method on list and print it. like
List<String> list = Arrays.asList(stringArray);
Collections.reverse(list );
System.out.println("Modified List: " + list );
You can use a Stack data structure that has LIFO behavior for insert and read of elements. Tha more complete Java Stack implementation is Deque that has the method "descendingOrder" that returns an iterator of elements in reverse order.
Deque deque = new LinkedList();
// We can add elements to the queue in various ways
deque.add("Element 1 (Tail)"); // add to tail
deque.addFirst("Element 2 (Head)");
deque.addLast("Element 3 (Tail)");
deque.push("Element 4 (Head)"); //add to head
deque.offer("Element 5 (Tail)");
deque.offerFirst("Element 6 (Head)");
deque.offerLast("Element 7 (Tail)");
Iterator reverse = deque.descendingIterator();
System.out.println("Iterating over Deque with Reverse Iterator");
while (reverse.hasNext()) {
System.out.println("\t" + reverse.next());
}
You can either use Collections.reverse() as suggested by other answers. But the standard way of reversing is done using Stack. Stack is a LIFO data structure which exactly exhibits your required behaviour. You'll need to push all your results to a Stack and pop it until Stack becomes empty. Something like below snippet will give you an outline.
String input = " Hello \n World \n Here you go";
List<String> inputList = Arrays.asList(input.split("\n"));
Stack<String> myStringStack = new Stack<>();
myStringStack.addAll(inputList); // This is to exhibit your input scenario from user.
while (!myStringStack.isEmpty()) { // While your stack is not empty, keep popping!
System.out.println(myStringStack.pop());
}

Returning ArrayList size does not work

When I run this program, it does not return anything yet no errors occur. I'm trying to create a method that will return the number of words I previously entered into the array once I enter "".
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayCounter {
public static int CountItems(ArrayList<String> list ) {
int i = list.size();
return i;
}
public static void main (String args[]) {
ArrayList<String> Names = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Hey gimme a word");
String word = input.nextLine();
if (word.equals("")) {
System.out.println("The number of values entered were:");
break;
} else {
Names.add(word);
}
}
CountItems(Names);
input.close();
}
}
You're ignoring the result returned from CountItems.
The println should be:
System.out.println("The number of values entered were: " + CountItems(Names));
As an aside, methods names in Java should start with a lowercase, so CountItems should instead be countItems.
Your CountItems method returns the item count, but you are ignoring the result. You need some kind of System.out.println(CountItems(Names)) to print the result to the console.
Also, please consider renaming CountItems to countItems and Names to names to follow the naming conventions for Java.

Separating an unknown amount of hyphens in java?

Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.

String split in two lists

I would like to split a line which might look like this:
6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0
The first value is x the second y.
Now i would like to have as a result two Lists ListX<Integer> and ListY<Double>.
I have tried doing it char by char. Where you can search for ':' and then go back and front to get the number. But there must be a faster way. Especially regarding on the lenght of the string which can get really big. Do You have any idea?
Thanks
You can try using String.split():
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
String[] splitString1 = test.split(" ");
String[] splitString2 = null;
for(String a : splitString1)
{
splitString2 = a.split(":");
System.out.println(splitString2[0]);
System.out.println(splitString2[1]);
//push splitString2[0] to x
//push splitString2[1] to y
}
Here is the complete code which does what you are thinking to do
import java.util.*;
public class IntegerDoubleExtractor{
public static void main(String []args){
String test = "6:8.0 7:36.0 14:9.0 15:31.0 22:5.0 23:21.0 30:2.0 31:12.0 38:40.0 39:137.0 46:50.0 47:133.0 54:35.0 55:106.0 62:16.0";
List<Integer> x = new ArrayList<Integer>();
List<Double> y = new ArrayList<Double>();
for(String xy : test.split(" ")) {
String xys[] = xy.split(":");
x.add(Integer.parseInt(xys[0]));
y.add(Double.parseDouble(xys[1]));
}
System.out.println(x);
System.out.println(y);
}
}
You can also use a Scanner and you won't need intermediate Strings or arrays in the process:
Scanner scanner = new Scanner(str);
scanner.useDelimiter(Pattern.compile("[:\\s]"));
while (scanner.hasNext()) {
listX.add(scanner.nextInt());
listY.add(scanner.nextDouble());
}

copyValueOf in Java?

import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
char[] course; //course code format: ABCDE##
String code;
//int num;
System.out.println("Input Course: ");
course = keyboard.next();
System.out.println(course);
code = String.copyValueOf(course, 0, 4);
System.out.println(code);
}
}
I don't know how I should let the user input the course when I'm using a character array instead of string. In short, how do I use the "scanner" on character arrays?
The instruction is the user will input a course code in the format: ABCDE##
Then, the program must split it into the course name and the course number. So, I had to use the copyValueOf method but it doesn't seem to work because from all the articles I read online, they used a char[] array but initialized the array with some value. So I was wondering how I could use the scanner on character arrays.
Why not just read a string from the scanner and then call String.toCharArray? It's not even clear why you need a char array here...
Why not just read a string directly with scanner.nextLine?
import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Input Course: ");
String course = keyboard.nextLine();
System.out.println(course);
String code = course.substring(0, 5); //You put 4 but it left out the last letter in the course name. I changed it to 5 and it worked but I'm confused since the index always start with 0.
System.out.println(code);
String num = course.substring(5, 6);
System.out.println(num);
}
}

Categories

Resources