I can get and print the integer value in java but I am confuse how to get and print string. Can someone help
package hello;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int integer;
System.out.println("Please Enter Integer");
Scanner sc = new Scanner(System.in);
integer = sc.nextInt();
sc.close();
System.out.println("you entered : " +integer);
}
}
Program output
Please Enter Integer
5
you entered : 5
I am stuck in this program. I don't understand how to get string and print on screen
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
int name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextInt();
sc.close();
System.out.println("Your name"+name);
}
}
You need to change your type value name from int to String. And replace sc.nextInt() by sc.nextLine() or sc.next().
Example
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name " + name);
}
Use sc.nextLine() for reading string inputs
or
sc.next() (But this will read only a word before it encounters a space)
You can also use InputStreamReader for this purpose
eg.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in()));
String input = br.readLine();
name = sc.nextInt(); doesn't work for strings, only for integers, you should use sc.nextline instead.
And also you have to change int name to String name, due to other type of variable.
Your code should look like this:
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}
change int name to string name and use sc.nextLine()
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
String name;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
name = sc.nextLine();
sc.close();
System.out.println("Your name"+name);
}
}
Related
I am trying to write a terminal-based toy app, which allows user to input product category and inventory.
Is it possible to implement a feature of pressing enter key to input the default inventory.
Here is the procedure/steps
app print "product category:"
user input a category, such as shoe
app print "Inventory(press enter key for 999):"
user press enterkey or input another number
app print product_category + product_inventory
here is my code
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
System.out.print("Inventory(press enter key for 999): ");
int product_inventory = scanner.nextInt();
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
this code does not support "enterkey for default" feature.
quesion
is it possible detect single enterkey with java.util.Scanner to implement the default input?
I also tried this code, even worse
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
scanner.close();
System.out.print("Inventory(press enter key for 999): ");
scanner = new Scanner(System.in);
String product_inventory_str = "999";
if(scanner.hasNext()){
System.out.println("hasNext");
product_inventory_str = scanner.nextLine();
}
else{
System.out.println("does not have Next");
}
int product_inventory = 999;
if(product_inventory_str.isEmpty()){
System.out.println("isEmpty");
}
else{
product_inventory = Integer.parseInt(product_inventory_str);
}
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
You could always read an entire line (because user will have to press Enter anyway) and then decide what to do with it, something like this:
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.nextLine();
System.out.print("Inventory(press enter key for 999): ");
String pi_string = scanner.nextLine();
int product_inventory = pi_string.isEmpty()?
999:Integer.parseInt(pi_string);
scanner.close();
System.out.println(String.format("%s, %d",
product_category, product_inventory));
}
When I input the following code into Eclipse I get the following error
"the method nextInt() is undefined for the type Scanner"
I am new to java any help is much appreciated
public class Scanner{
public static void main(String[]args) {
Scanner person = new Scanner();
System.out.print("Enter age: " );
int age = person.nextInt();
System.out.print("Enter gender male/female: ");
String gender = person.nextLine();
}
}
Your classname is Scanner. You should rename your class as ScannerTest and import java.util.Scanner; Also pass System.in as parameter to your Scannerclass.
import java.util.Scanner;
public class ScannerTest {
public static void main(String[]args) {
Scanner person = new Scanner(System.in);
System.out.print("Enter age: " );
int age = person.nextInt();
System.out.print("Enter gender male/female: ");
String gender = person.nextLine();
}
}
first thing is you need to change your class name.
Then type import java.util.Scanner; above your class
Then you need to add system.in as new Scanner(system.in);
my trial:
package test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner person = new Scanner(System.in);
System.out.print("Enter age: " );
int age = person.nextInt();
System.out.print("Enter gender male/female: ");
String gender = person.nextLine();
}
}
import java.util.Scanner;
public class IfAndString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
char a = line.charAt(2);
char b = line.charAt(2);
if (a < b)
System.out.printf("%s starts with 'a'.",a);
else if (a > b)
System.out.printf("\n%s does not start with 'a'.",b);
}
}
You can use the startsWith() method
Example:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
if (line.startsWith("a"))
{
System.out.println(line + ": starts with a");
}
else
{
System.out.println("does not start with a");
}
}
Also if you wanted to check for an a even if they entered an uppercase A you could change your line variable to lower case in the if check to account for both lowercase and uppercase a.
Example:
if (line.toLowerCase().startsWith("a"))
Anwser to your question in the headline. Simply use the Method boolean startsWith(String string) method from the String class, e.g. like this:
import java.util.Scanner;
public class IfAndString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Word:");
String line = input.next();
if (line.startsWith("a")){
System.out.printf("%s starts with 'a'.",a);
} else{
System.out.printf("\n%s does not start with 'a'.",b);
}
}
}
When you want to compare chars do something like this:
"abc".charAt(0) == 'a'; // String implement CharSequence.
I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. I was encouraged to use a for loop, but I don't see how that would work. I can calculate the number of characters using length(), but I can't figure out how to make my method work. This is what I have so far:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
return;
}
public static int GetNumOfCharacters(int userCount) {
int i = 0;
String userInput = "";
userCount = userInput.length();
return userCount;
}
}
My method is not returning the length of the string, it just gives me 0 or an error.
Right now, you are never calling your "GetNumOfCharacters" method in your main. The way Java programs work, is by calling the main method and executing line per line what lies there. So you need to call you method from inside the main method. On the other hand, it should get the Stirng as a parameter, so you can get its length. It would look something like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
int lenInput = GetNumOfCharacters(userInput);
System.out.println("The length was: "+lenInput+" characters");
}
public static int GetNumOfCharacters(String userInput) {
int len = userInput.length();
return len;
}
A problem is that you are not actually calling the method
so try
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.print("You entered: ");
System.out.println(userInput);
System.out.println ("The length is " + GetNumOfCharacters (userInput))
}
// need to pass string into this method
public static int GetNumOfCharacters(String myString) {
int userCount = myString.length();
return userCount;
}
}
Your question included the line:
I was encouraged to use a for loop, but I don't see how that would
work.
There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string:
for (int len = 0; ; len++) {
try {
text.charAt(len);
} catch (StringIndexOutOfBoundsException ex) {
return len;
}
}
That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop.
Problems with your code:
No Function call
Add function call in main() as int count=GetNumOfCharacters(userInput);
Parameter datatype mismatch
change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) {
Unwanted return statement in main()
remove the return from main()
Not displaying the value returned from GetNumOfCharacters
Add System.out.print("Number of characters: "+ count); inside main()
Code:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
int count=GetNumOfCharacters(userInput);
System.out.print("Number of characters: "+ count);
}
public static int GetNumOfCharacters(String userInput) {
int userCount = userInput.length();
return userCount;
}
OR
Function is not really needed,you can remove the function and do it like this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter a sentence: ");
System.out.print("You entered: ");
userInput = scnr.nextLine();
System.out.println(userInput);
System.out.print("Number of characters: "+ userInput.length());
}
If you don't want to use predefined methods, you can do like this..
public static void main(String args[]){
Scanner scnr = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String userInput = scnr.nextLine();
System.out.println("You entered: "+userInput);
char a[]=userInput.toCharArray();
int count=0;
for(char c : a){
count++;
}
System.out.println("length of the string is:"+count);
}
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first string: ");
String one = input.nextLine();
System.out.println("Please enter the second string: ");
String two = input.nextLine();
.....
Try this:
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first string: ");
String one = input.nextLine();
System.out.println("Please enter the second string: ");
String two = input.nextLine();
StringBuilder sb = new StringBuilder();
for (int i = one.length() - 1, j = two.length() - 1; i >= 0 && j >= 0; i--, j--) {
if (one.charAt(i) != two.charAt(j)) {
break;
}
sb.append(one.charAt(i));
}
System.out.println(sb.reverse().toString());
}
}
I hope, that this piece of code is self-explanatory.
You can also use Google Guava to find a common suffix:
com.google.common.base.Strings.commonSuffix(str1, str2)
import java.util.Scanner;
import com.google.common.base.Strings;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first string: ");
String one = input.nextLine();
System.out.println("Please enter the second string: ");
String two = input.nextLine();
System.out.println("Common suffix: " + Strings.commonSuffix(one, two));
}
}