I wanna make a condition if somebody input a word the program will return "That is a string" if it is an integer the program will return "That is an integer ". What's wrong with my if condition ?
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
if (skaner.next() != int) {
System.out.println("That is a string" + skaner.next());
}
else {
System.out.println("That is an integer " + skaner.next());
}
}
skaner.close();
}
}
Here skaner.next() will return a String object whereas int is a primitive data type and therefore both are not comparable. To check if token returned by skaner.next() is an int or not, you can use Integer.parseInt(skaner.next()) which converts String to int and throws a NumberFormatException if input is not a valid integer.
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
String x = skaner.next();
try {
int y = Integer.parseInt(x);
System.out.println("That is an integer " + y);
}
catch(NumberFormatException e) {
System.out.println("That is a string " + x);
}
}
skaner.close();
}
}
Check this link for reference.
Related
When calling scanDouble(); I get an error.
package com.company;
import java.util.Random;
import java.util.Scanner;
public class Main {
Scanner in = new Scanner(System.in);
public static void printLogarithm(double x){
if(x <= 0.0){
System.err.println("Error: x must be positive.");
return;
}
double result=Math.log(x);
System.out.println("The log of x is"+ result);
}
public static void scanDouble(Scanner in) {
System.out.print("Enter the name: ");
if (!in.hasNextDouble()){
String word = in.next();
System.err.println(word + "is not a number");
return;
}
double x = in.nextDouble();
printLogarithm(x);
}
public static void main(String[] args) {
scanDouble();
}
}
Does anyone know how to execute scanDouble(); Is there something I should include in the method call?
If I follow your logic, try passing the Scanner variable in inside the scanDouble() method like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
scanDouble(in);
}
Passing a double value x for instance as an argument won't work, I just tested it.
I use nextLine to read user's input and split by spaces.
And treat user's inputs as float.
However the output are not the same as the original user inputs.
How could I fix it?
Output
Enter 2 floats divided by a space12.31 2213.12
you entered 12.310000 and 2213.120117 successfully
Process finished with exit code 0
Expected output
Enter 2 floats divided by a space12.31 2213.12
you entered 12.31 and 2213.12 successfully
Process finished with exit code 0
my source code
private static float[] getTwoFloats(){
Scanner rd = new Scanner(System.in);
while (true){
System.out.print("Enter 2 floats divided by a space");
try{
String toks[] = rd.nextLine().split(" ");
if(toks.length==2){
float[] rtnFloats = new float[2];
for(int i=0; i < 2; i++){
rtnFloats[i] = Float.valueOf(toks[i]);
}
return rtnFloats;
}
}catch (Exception e){
}
}
}
public static void main(String[] args) {
float[] twoFloats = getTwoFloats();
System.out.printf("you entered %f and %f successfully", twoFloats[0], twoFloats[1]);
}
Use System.out.println instead of System.out.printf.
System.out.println("you entered " + twoFloats[0] + " and " + twoFloats[1] + " successfully");
I'm not sure about why exactly does this work and whats the difference between the two but I'll investigate. Maybe someone with better understanding can explain?
You should convert the data type while you use it, for print out, just store the inputs as string.
private static String[] getTwoFloats() {
Scanner rd = new Scanner(System.in);
while (true) {
System.out.print("Enter 2 floats divided by a space");
try {
String toks[] = rd.nextLine().split(" ");
return toks;
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
String[] twoFloats = getTwoFloats();
System.out.printf("you entered %s and %s successfully", twoFloats[0], twoFloats[1]);
}
OUTPUT:
Enter 2 floats divided by a space55.248 5465.5645
you entered 55.248 and 5465.5645 successfully
=================UPDATE=====================
For the worries of #HarshilSharma, we can do it as below.
public static class FloatObj {
private float value; // Store original string for printing
private String str; // Store value for calculation
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
private static FloatObj[] getTwoFloats() {
Scanner rd = new Scanner(System.in);
while (true) {
System.out.print("Enter 2 floats divided by a space");
try {
String toks[] = rd.nextLine().split(" ");
if (toks.length == 2) {
FloatObj[] result = new FloatObj[2];
for (int i = 0; i < 2; i++) {
FloatObj floatObj = new FloatObj();
floatObj.setStr(toks[i]);
floatObj.setValue(Float.valueOf(toks[i]));
result[i] = floatObj;
}
return result;
}
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
FloatObj[] results = getTwoFloats();
System.out.printf("you entered %s and %s successfully", results[0].getStr(), results[1].getStr());
}
I am basically making a hangman game...
package wordguessinggame2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordGuessingGame2 {
private static String playerInput;
private static String randomWord;
static class RandomWordProvider {
public final List<String> words;
public RandomWordProvider() {
words = readFile();
}
public int randomInteger() {
int randomInt = (int) (Math.random() * words.size());
return randomInt;
}
public String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
private List<String> readFile() {
List<String> wordsList = new ArrayList<>();
try {
File fourLetterWords = new File(System.getProperty("user.home"),"Documents/FourLetterWords.txt");
Scanner in = new Scanner(fourLetterWords);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line!=null && !line.isEmpty()) {
wordsList.add(line);
}
}
}
catch (FileNotFoundException ex) {
System.out.println("\nFile not found.");
System.exit(0);
}
return wordsList;
}
}
public WordGuessingGame2(String playerInput) {
WordGuessingGame2.playerInput = playerInput;
}
public String getPlayerInput() {
return playerInput;
}
public void setPlayerInput(String playerInput) {
WordGuessingGame2.playerInput = playerInput;
}
public static class PlayerCharacterEntry{
private String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
public static void main(String[] args) {
Scanner wantToPlay = new Scanner(System.in);
System.out.print("Welcome to the word guessing game! Would you like to play? ");
String playerAnswer = wantToPlay.next();
if (playerAnswer.equalsIgnoreCase("Yes")) {
System.out.print("\nYour objective is to guess a four letter word by entering"
+ "\nletters on your keyboard. If you can not guess the word in seven attempts,"
+ "\nyou lose! You will be told if the letter you entered is in the word, and"
+ "\nyou will be told if the letter you entered is not in the word. You will be"
+ "\nallowed to guess the word any time during your seven attempts. If at anytime"
+ "\nyou would like to terminate the game, enter the word 'terminate'. Good Luck!"
+ "\n \n");
}
if (playerAnswer.equalsIgnoreCase("No")) {
System.out.print("Maybe another time!");
System.exit(0);
}
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
if (randomWord.contains(playerInput)){
System.out.println(playerInput);
} else {
System.out.println("That letter is not in the word!");
}
}
}
Here at the bottom I am trying to determine if the letter that the player enters is in the word, then to display that letter, but when I run the program and I input a letter, I get a NullPointerException where I say:
if(randomWord.contains(playerInput))
I believe it has something to do with randomWord but I don't know how to fix it.
You never assign anything to WordGuessingGame2.randomWord to it stays null.
You need to replace
randomWordProvider.getWord();
with
randomWord = randomWordProvider.getWord();
you have to put a correct path.. try this :
File fourLetterWords = new File(System.getProperty("user.home"),"/Documents/FourLetterWords.txt");
you never initialize the class variable randomWord
I want my program to execute the first return statement if the conditions are true otherwise return it as normal.
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
return answer;
}
}
Well, in your code you don't need to return anything.
But, if you want to return something you are in the wrong method.
main is a "special" method, it cannot return anything (well, in other languages it might return an int which is the exit status, but ignore it here) and is where your code starts.
If you want to return something you should write a method.
A method is a block of code which is execute when you call it and can return value back to who called it. In this case your method will be static because you will call it from the main method which is static
public static int methodName()
{
int X, Y;
int answer;
if (x == y)
{
// Do something
return returnSomethingBackTomain;
}
else
{
return returnSomethingOfDifferentTomain;
}
}
Well.. it could be your method
public static int methodName()
{
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
}
else {
System.out.println("These two numbers are not the same, but they equal: " + answer);
}
return answer;
}
But please be more specific on what you want to do.
Because i dont see any reason to write a such method.
If your main function is void, you don't have to return anything, you can just use
return;
That gives:
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
But you can also do:
...
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
} else {
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
}
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y)
System.out.println("These two numbers are the same and they equal: " + answer);
else
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
main has a void return type, so no need to return anything.
By the way, try to fit CQS principle.
Indeed, printing something is a side-effect operation, so no need to return anything but void.
You're making a few mistakes.
The main method should never be used to return a value.
The main method is the entry point to your program.
Here you declare methods to be run at the start of the program. In GUI-projects, this is used to load the inital GUI (Forms).
Also, a void method cannot return something.
When initalising a method, you have to declare what type the returned value will have.
Void means that there is no data returned.
You will have to write a method which you can call to receive your data.
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
return answer;
}
Now you can initalize your class (e.g. Scanner) and call the method scanForEqualNumbers.
Scanner scanner = new Scanner();
int result = scanner.scanForEqualNumbers();
If you don't want to have to initialize a class to call the method, you can declare the scanForEqualNumbers as static.
public static int scanForEqualNumbers() { ...
Then you can call this method directly as this:
int result = Scanner.scanForEqualNumbers();
1 more note.
You don't need the return in the IF-statement.
As you return the answer anyway, you can keep the print the the IF-statement and use the return after it.
You could also return -1 as answer in an ELSE-statement so you can use this answer in further methods. This way you can check the result of the method without having to read the console output.
I even suggest to make a seperate class for this.
You'll need your Main-method to run your program. This'll also be the location of your method class.
public class MyApp {
public static void main(String[] args) {
MyScanner myScanner = new MyScanner();
int result = myScanner.scanForEqualNumbers();
System.out.format("The scanned numbers %s equal", result > 0 ? "ARE" : "are NOT");
}
}
public class MyScanner {
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
/* This can be replaced, see below
int answer = x + y;
if (x != y) {
answer = -1;
}
return answer;
*/
// IF X equals Y ? return X + Y : ELSE return -1
return (x == y ? x + y : -1);
}
}
I'm getting an error at the 2nd class c.getResponse
The method getResponse(String) is undefined for the type BotTest
If anyone wants to see what the assignment was heres the pdf:
http://www.cs.stonybrook.edu/~tashbook/fall2013/cse110/project-1.pdf
import java.util.*;
public class ChatBot {
public String getResponse(String input) {
int i = 0;
int found = input.indexOf("you", i);
if (found == -1)
return "I'm not important. Let's talk about you instead.";
int x = longestWord(input).length();
if (x <= 3) {
return "Maybe we should move on. Is there anything else you would like to talk about?";
}
if (x == 4) {
return "Tell me more about" + " " + longestWord(input);
}
if (x == 5) {
return "Why do you think" + " " + longestWord(input) + " "
+ "is important?";
} else if (x > 5) {
return "Now we are getting somewhere. How does" + " "
+ longestWord(input) + " " + "affect you the most";
}
else
return "I don't understand";
}
private String longestWord(String input) {
String word, longestWord = "";
Scanner turtles = new Scanner(input);
while (turtles.hasNext()) {
word = turtles.next();
if (word.length() > longestWord.length())
longestWord = word;
}
return longestWord;
}
}
Second Class to test the code
import java.util.*;
public class BotTest {
public static void main(String[] args) {
Scanner newturtles = new Scanner(System.in);
System.out.println("What would you like to talk about?");
String input = newturtles.nextLine();
BotTest c = new BotTest();
while (!input.toUpperCase().equals("GOODBYE")) {
System.out.println(c.getResponse(input));
input = newturtles.nextLine();
}
}
}
getResponse is defined for ChatBot not BotTest
ChatBot c = new ChatBot();
The Class BotTest indeed does NOT have the .getResponse(String) function. ChatBot does though.