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);
}
}
}}
Related
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int A = sc.nextInt().split(":");
int B = sc.nextInt();
System.out.println(A + B);
}
}
If I'm given an input like 1:2 then the output should be 3. Likewise 54:6 then 60.
But I'm getting an error. What should I do to achieve that output?
You cannot call split on an integer, it is meant for splitting a String. Try this:
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] numbers = sc.next().split(":");
int A = Integer.parseInt(numbers[0]);
int B = Integer.parseInt(numbers[1]);
System.out.println(A + B);
}
}
Of course some validation would be nice (check if the String contains a colon, if the parts are numeric, etc.), but this should point you in the right direction.
At first, read a whole input line into a String variable. Then just split it into two values and cast them to integer.
Code example:
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
String[] splittedValues = inputString.split(":");
int
A = Integer.parseInt(splittedValues[0]),
B = Integer.parseInt(splittedValues[1]);
System.out.println(A + B);
you will need to take input as string and then split your input by : and convert the string to integer and add them.
see example below
public class Hello {
public static void main(String[] args) {
String input;
Scanner sc = new Scanner(System.in);
input = sc.next();
String[] parts = input.split(":");
if(parts.length > 0) {
int sum = Integer.parseInt(parts[0])+Integer.parseInt(parts[1]);
System.out.println(sum);
} else{
System.out.println("Enter number in format example 12:2");
}
}
}```
You can try this:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
sc.next().charAt(0);
int B = sc.nextInt();
System.out.println(A + B);
}
}
I think Splitting of two integers is not possible in java(it is possible in python by using the input.split() function) ,for that reason it is better take input as string and split input by using colon(:) operator and convert those input string to an integer and add the both to print the result.
java code:
import java.util.Scanner;
Public class TwoIntegers
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in());
String[] two_numbers = s.next().split(":");
int fir_num = Int.parseInt(two_numbers[0]);
int sec_num = Int.parseInt(two_numbers[1]);
int sum=fir_num+sec_num;
System.out.println("The sum of two numbers is:"+sum);
}
}
In the code below, at the bottom, for some reason although I assign the value of encodingCharacter = encodeArray[j];. After that I try to print that specific subscript value out. But for some reason that statement is causing issues. After I run the program I see that it ran 2 empty lines, I don't know why I can't assign the char value 'z' to encodingCharacter.
import java.util.Scanner;
public class UserInputDemo1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//creating scanner named input.
System.out.println ("Would you like to encode or decode a message.");
System.out.println ("If you would like to encode a message enter true. If you would like to decode a message enter false");
System.out.println("Note that blank spaces are seperated by a space and the message terminates with a period.");
boolean encodeOrDecode = input.nextBoolean();
if (encodeOrDecode)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the message you would like to be encoded.");
String encodeMessage = scan.nextLine();
char[] encodeCharArray = encodeMessage.toCharArray();
encodeMessage(encodeCharArray);
}
if (!encodeOrDecode)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the message you would like to be decoded.");
String decodeMessage = scan.nextLine();
char[] decodeCharArray = decodeMessage.toCharArray();
}
}
public static void encodeMessage (char encoding [])
{
char encodeArray [] = new char [encoding.length];
for (int j = 0; j < encoding.length; j++ )
{
char encodingCharacter = encoding[j];
if (encodingCharacter == 'a')
{
encodingCharacter = 'z';
System.out.println(encodingCharacter);
encodingCharacter = encodeArray[j];
System.out.println(encodeArray[j]);
}
if (encodingCharacter == 'b')
{
encodingCharacter = 'y';
System.out.println(encodingCharacter);
encodingCharacter = encodeArray[j];
}
}
String encodedArray = new String(encodeArray);
System.out.println (encodeArray);
}
}
At line 15 is where the java.util.InputMismatchException occurs.
Your input.nextBoolean() returns whether the next token of the input is a boolean, rather than whether there is another character.
I believe you are looking for input.hasNext(), or something of the sort.
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 !");
}
}
}
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));
}
}
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".