I am currently learning how to use Array lists in Java and i am stuck on a simple but annoying problem..
import java.util.*;
public class ReplacingALetter
{
public static void main (String[] args)
{
String word = "Banana";
List underscore = new ArrayList(word.length());
int i;
for (i=0; i<word.length(); i++)
{
underscore.add(i, "x");
}
System.out.print(underscore);
System.out.println();
System.out.print("Enter a letter: ");
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (sc.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
System.out.print(underscore);
}
}
For some reason it is not substituting the first x in the array 'underscore' with the letter B :/
The Output of that code is [ x x x x x x ]
But when i enter this code:
import java.util.*;
public class ReplacingALetter
{
public static void main (String[] args)
{
String word = "Banana";
List underscore = new ArrayList(word.length());
int i;
for (i=0; i<word.length(); i++)
{
underscore.add(i, "x");
}
System.out.print(underscore);
System.out.println();
System.out.println("Switching First x with B: ");
underscore.set(word.indexOf("B"),"B");
System.out.print(underscore);
}
}
It works Perfectly and the output is [ B x x x x x ]
Can't figure out what i'm doing wrong....
The only difference I spotted in your 2 examples is, that one uses a if condition:
if (sc.equals("B")) {
underscore.set(word.indexOf("B"),"B");
}
whereas the other one executes
underscore.set(word.indexOf("B"),"B");
unconditionally. Your sc is a java.util.Scanner, "B" is a string. They can't be equal, so the method is never called in your first example.
if (sc.equals("B")) this condition is always false because sc is not an object of class String.
You should change your code to:
if (letter.equals("B")) {
underscore.set(word.indexOf("B"),"B");
}
if (letter.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
you have to check if letter is equal to B not sc is equal to B.
String letter = sc.nextLine();
if (letter.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
Modify this snippet
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (sc.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
to
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (letter.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
In the former you are comparing Scanner object with the string "B" which will never be equal.
In the latter it compares the string read from standard input to "B".
Related
In a part of my program, I put a while loop to repeatedly ask for inputs. There is an option to type in the letter "F" and break the loop.
This is my program:
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
while (x==0) {
System.out.println("Type your number:");
Scanner s = new Scanner(System.in);
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}
}
When I run the program, I type some numbers and then type "F". I see this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "F"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Example.main(Example.java:13)
I believe the String "F" can pass through my else if but I don't know why. How can I solve this?
You are comparing a string with a Scanner obj. Lets see how a scanner object works in java.
Scanner myObj = new Scanner(System.in);
String myInput = myObj.nextLine(); // Read user input
Then you can compare your myInput to the character 'f' or 'F'
You cannot directly compare a scanner object with a string. You will need to take some input using scanner and then you can compare that input with other types.
Try running this code.
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
Scanner sc = new Scanner(System.in);
while (x==0) {
System.out.println("Type your number:");
String s = sc.nextLine();
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}}
Requirement:
Ask the user to type a single character from the alphabet.
Indicate then that this character is vowel or consonant, depending on the user's input.
If the user input is not a letter (between a and z or A and Z), or is a word with length> 1, type an error message.*
Problem:
can anyone help me to fix this code for the bold one , i have to use character not String.
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("put an character of alphabet : ");
char s = sc.next().charAt(0);
int s1 = s;
String s2 = Character.toString(s);
if(s2.length() > 1){
System.out.println(" Mistake !");
}
}
}```
There are lots of ways of doing it but you can simply check if there are more chars on your Scanner, ex:
if (sc.hasNext()) {
System.out.println(" Mistake !");
}
This way, if you scanner has another input, you will get the Mistake printed.
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("put an character of alphabet : ");
char s = sc.next().charAt(0);
int s1 = s;
String s2 = sc.next();
if(s2.length() > 1){
System.out.println(" Mistake !");
}
}
}
But you can optimize your program as below,
public class Ush {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("put an character of alphabet : ");
String s2 = sc.next();
char s = s2.charAt(0);
int s1 = s;
if(s2.length() > 1){
System.out.println(" Mistake !");
}
}
}
Can you please tell me what is wrong with the following java code.
I am trying to collect input from the user through Scanner class object then store it in an array by using while but it would be infinite loop if i don't supply a break condition , so i thought to break when the input equals "q", but it didn't work.
import java.util.*;
public class ProjectOne{
public static void main (String []arg){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String x = input.next();
while ( input.hasNext()){
if (x !="q"){
one.add(input);
}
if (x == "q")
{
break;
}
System.out.println(one);
}
}
}
You don't compare String with ==. Use .equals() like
if (!x.equals("q")){
and
if (x.equals("q"))
Note : I think that you aren't using Scanner correctly. You take the input, but keep checking x, instead of the input.
Do not compare strings like x =="q"
USE .equals function in java for string comparison.
Replace your code with: x.equals("q") for x =="q" and !x.equals("q") for x !="q"
You are not reading updated value from Scanner. Below is updated code for your reference after correcting formatting and other errors. Also, instead of == sign, use equals() method for string comparison -
import java.util.*;
public class ProjectOne{
public static void main (String []arg ){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String x = null;
while ( input.hasNext()) {
x = input.next();
if (!x.equals("q")) {
one.add(x);
}
if (x.equals("q")){
break;
}
}
System.out.println(one);
}
Scanner reads everything before your ENTER - the whole line you input.
I think that is what you need:
import java.util.ArrayList;
import java.util.Scanner;
public class ProjectOne
{ public static void main (String []arg ){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String pattern;
String x = input.next();
while (true){
String line = input.next();
if(line.contains("q"))break;
else{
x = x + " " + line;
}
}
System.out.println(x);
}
import java.util.Scanner;
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
for(int i=0; i<w.length();i++)
System.out.println(w.charAt(i));
}
}
This is what I have so far and I can't figure how to make it so that if the word is 5 letters or longer to print it one letter per line and if not to just print the word. So far it'll just print any word with one letter per line.
You are very close. The only thing missing is an if-else conditional statement, to check whether the word has a length of five. Without this check, you will always print the string one character per line, regardless of its length.
import java.util.Scanner;
public class SeperateLetters {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w = scan.nextLine();
if (w.length() >= 5) { // print one char per line if length is 5
for (int i = 0; i < w.length(); i++)
System.out.println(w.charAt(i));
} else {
System.out.println(w); // otherwise, print the whole string
}
}
}
Use an if-else statment to check if w.length() == 5 or not.
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
if( w.length() > 5)
{
for(int i=0; i<w.length();i++)
{
System.out.println(w.charAt(i));
}
}
}
}
So I'm new to Java and I figured I'd do something simple like a for loop to print out an array of strings or something,
My code ended up like this:
package package.four;
import java.util.Scanner;
public class arrayrecurse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter 5 words");
String a = in.next();
String b = in.next();
String c = in.next();
String d = in.next();
String e = in.next();
String[] s = {a, b, c, d, e};
for(int i = 0; i< s.length;){
System.out.println(s[i]);
i++;
}
in.close();
}
}
It works fine but my question is if it's possible to make a for loop cycle through variables.
For examples if I wanted something like:
for(words = 5; words > 0;){
String a = in.next();
a++}
Where would it change the variables each time I enter a new word.
Would it be possible to do something like that or do I need to type out the String variable = in.next(); every time I want to enter a new word input from the console?
You can call next() inside the loop, but you need to declare the variable outside the loop if you want to use it afterwards, also, there is no ++ operator for String or array in Java:
String[] inputs = new String[5];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
Use an ArrayList to store the input variables.
That is:
import java.util.*;
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (String s: inputVars)
{
System.out.println(s);
}
}
Or alternatively, if you want to change the contents of the ArrayList:
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (int i = 0; i < inputVars.size(); i++)
{
System.out.println(inputVars.get(i));
//Change the variable
inputVars.set(i, "Hello, " + inputVars.get(i));
}
}