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!
Related
Ask the user to enter in a number, then you can print out the number of many * on the screen without spaces or newlines. You may use your Scanner object in numbers 5, 6 and 9 also.
Input:
7
Output:
*******
I can do this but I can't do it in a single line all the astericks
import java.util.Scanner;
class {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x;
int i;
System.out.println("Enter a number:");
x = scan.nextInt();
for (i = 0; i < x; i++) {
System.out.println("*");
}
}
}
You can use a for-loop like so changing println to just print so you print the * on the same line:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number:");
int inputNumber = sc.nextInt();
for(int i=0;i<inputNumber;i++) {
System.out.print('*');
}
}
}
Try it here!
Note: You can initialize i within the for-loop and don't need to declare it beforehand
It's my first response i hope to help you...
Try
System.out.print("*");
if you use
System.out.println("*");
Your program will do a line jump...
To print all the asterisks in a single line, use print instead of println:
Scanner scan = new Scanner(System.in);
int x;
int i;
System.out.println("Enter a number:");
x = scan.nextInt();
for (i = 0; i < x; i++) {
System.out.print("*"); // <- note the difference here!
}
Why? Let's look at the docs:
print(String):
Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
println(String):
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
So println(String) calls print(String) then println(). What does println() do?
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
Now you see the difference! println(String) prints a new line after it prints the string while print(String) does not!
Here's a cleaned up version of your code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int x = scan.nextInt();
for (int i = 0; i < x; i++) {
System.out.print("*");
}
You should to use
System.out.print("*");
and not
System.out.println("*");
Because println return to line and print not.
Hope this can help you.
Note
Your class need a name in your question you do :
class {
and this wrong in java, so you need to declare your class like this:
class nameClass {
//Your code
}
Take a look here :
Getting Started
and here:
Arrays
I'm having trouble activating my counter++. So far s2 is able to read s1, but cannot count amount of occurrences. Any help would be appreciated. (I realize that I am working in the wrong string, but it helps me to create the solution here first and then send it to a second string, is this poor logic?)
Sorry for the dumb question I am very new at programming
//i need a scanner that reads what i write that scanner should count
occurrences of a char another scanner declared scanner a would ask " write something" string s. = nextline etc new scanner asks for a letter string s1 = next line blb that input = something int count = StringUtils.countMatches(s1); System.out.print(amount ) i
//
public class Task07 {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("write something");
String text = s1.nextLine(); //reads user input value
Scanner s2 = new Scanner(System.in); // missing smth that limits length of s2
System.out.println("geb a letter");
String letter = s2.nextLine();
int counter = 0;
boolean found;
found = text.contains(letter);
if (found == true) {
counter++;
} else {
System.out.println(counter);
}
// could use counter from 6 here but need a way to tell counter
// that it should add +1 for every time something occurs in
// the other scanner
/*
Problems: text recognizer is boolean only
- doesnt activate counter
- doesnt activate counter based on X times occurence
- doesnt limit "letter" to only one char
-
*/
}
}
Basically a loop is the simple way to count character occurrences in a string. You would use something like
int counter = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == letter.charAt(0)) {
counter++;
}
}
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.
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The children are playing with their toys because they love it.
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String a = input.nextLine();
String b = input.nextLine();
String z[] = b.split(" ");
int number=0;
for (int i =0; i<z.length; i++){
if (z[i].contains(a))number++;
}
System.out.println(number);
I won't give you too much code, but here are the main talking points:
You need a way to read the input in. This can be accomplished with a Scanner - it's either from STDIN or a file.
You need a way to break up each word in the sentence. String#split will help you with that.
You need a way to ignore the casing of each sentence - toLowerCase() works well here.
You need to loop over each word in one sentence, as well as each occurrence in the other sentence. Consider that String.split produces a String[], and you can iterate over that with any standard for loop.
You need a way to see is a string is contained in another string. String#contains will help - although you want to be very careful on which side you're asking contains a string. For example:
// This will print true
System.out.println("The world".toLowerCase().contains("the"));
// This will print false
System.out.println("the".contains("The world".toLowerCase()));
Try this :
import java.util.Scanner;
public class Occurence {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine();
String str2 = input.nextLine();
int count = 0;
String word[] = str1.split(" ");
for (int i = 0; i < word.length; i++) {
if (word[i].toLowerCase().contains(str2.toLowerCase())) {
count++;
}
}
System.out.println("Occurence = " + count);
}
}
I need to concatenate output from a loop. User input will determine for how long it will last. I'm am trying to generate a password with generating a random number and then converting the number into ASCII character (all lowercase characters currently). Instead of having multiple for() how is it possible to concatenate the out put into one string based on the user input?
import java.util.Random;
import java.util.Scanner;
public class Password
{
public static void main (String[] args)
{
int randNum=0;
int min=97;
int max=122;
int az=0;
String b="";
String c="";
Scanner in= new Scanner (System.in);
Random randNumlist= new Random();
System.out.println("lowercase letters [a]");
String input= in.next();
System.out.println(" how many characters (max 14)");
int input2=in.nextInt();
if ( input.equalsIgnoreCase("A"))
{
while(!(randNum>=96 && randNum<=123))
{
for (int n=1; n <=input2; n++)
{
randNum= randNumlist.nextInt((max-min)+1)+min;
az =+randNum;
char p= (char)az;
b = new StringBuilder().append("").append(p).toString();
System.out.println(b);
}
}
}
}
}
Example input: a or A
2nd Example input: numbers 1-14
Example output:
a
e
b
h
Desired output: aebh
Several points:
Your for loop is pointless. You initialise n to input2 then loop until n == input2 meaning one iteration
Your while loop is pointless and will only also iterate once as randNum is set to between 96 and 123 in the first iteration
Declare your StringBuilder outside of the loop. Currently you create one for each iteration (which is only once) which means the previous String will be lost. Then in your loop just call the append method.
Print after the loop by calling the toString() method of your StringBuilder.
So something like this
StringBuilder sb = new StringBuilder()
//Start Loop
sb.append("Your character here");
//End Loop
System.out.println(sb.toString());