"if" doesn't work with "keyboard.nextLine()" - if-statement

I would have to write the correct password and if it is correct it say "password is correct"
When I write the correct password it say that it isn't correct.
Her is my code:
import java.util.Scanner;
class myclass
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String name;
String password;
System.out.println("give your name:\t");
name=keyboard.nextLine();
System.out.println("Hello"+name);
System.out.println("give your password:\t");
password=keyboard.nextLine();
keyboard.close();
if (password=="www")
{
System.out.println();
System.out.println("password is correct") ;
}
else
{
System.out.println();
System.out.println("password isn't correct");
}
}
}

You have to use the method equals instead of == then it will work.
Looks like that:
import java.util.Scanner;
class myclass {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
String name;
String password;
System.out.println("give your name:\t");
name = keyboard.nextLine();
System.out.println("Hello" + name);
System.out.println("give your password:\t");
password = keyboard.nextLine();
keyboard.close();
if (password.equals( "www")) {
System.out.println();
System.out.println("password is correct");
} else {
System.out.println();
System.out.println("password isn't correct");
}
}
}
Output:
give your name:
name
Helloname
give your password:
www
password is correct

You should not compare String using == operator. You should use equals method to compare String object. e.g. "www".equals(password)

Related

push_back getting a vector of last element by self created object

I'm trying to read in a list of Animals, this works fine. Then I want to split each string into two substrings for the name and cmc, this also works fine. But my cout doesn't work.
For example, my animal.txt is:
Dog|hi
cat|miau
cow|hihi
My output of the for loop should look like this:
Dog
cat
cow
But the actual output is:
cow
cow
cow
Here is my Animal.cpp:
#include <string>;
#include <vector>;
#include <fstream>;
#include "Animal.h"
using namespace std;
string cmc;
string name;
void Animal();
void Animal(string nameA) {
name = nameA;
}
void Animal(string nameA, string cmcValue) {
name = nameCard;
cmc = cmcValue;
}
void Animal::setName(string names)
{
name = names;
}
void Animal::setCmc(string cmcvalue) {
cmc = cmcvalue;
}
std::string Animal::getName() {
return name;
}
std::string Animal::getCmc() {
return cmc;
}
void Animal::openfileAnimal() {
ifstream inFileAnimal;
inFileAnimal.open("Animals.txt");
if (inFileAnimal.fail()) {
cerr << "error open this file" << endl;
exit(1);
}
string itemsAnimal;
std::vector<Animal> AllAnimals;
while (getline(inFileAnimal, itemsAnimal)) {
Animal c;
string t1 = itemAnimal;
size_t pos = t1.find("|");
//name (setname(sub))
string sub = t1.substr(0, pos);
c.setName(sub);
string t2 = t1.substr(sub1.length() + 1, t1.length());
string sub2 = t2.substr(0, t2.length());
c.setCmc(sub2);
AllAnimals.push_back(c);
}
for (int i = 0; i < 2; i++) {
std::cout <<AllAnimals.at(i).getName() << endl;
}
}
I read nother StackOverflow questions like mine, but for my example all the solutions don't work. So where is my problem? I guess it's something like I am modifying the same memory over and over.
You have global variables instead of class data members:
string cmc;
string name;
void Animal();
void Animal(string nameA) {
name = nameA;
}
void Animal(string nameA, string cmcValue) {
name = nameCard;
cmc = cmcValue;
}
As a result, you keep only the latest assigned values. Moreover, something that you probably treat as a constructor, is not a constructor at all. The constructor should look like:
Animal::Animal(string nameA, string cmcValue)
: name(nameA), cmc(cmcValue) {
}
Note that initialization list syntax: that allows to avoid the mistakes like your's.
By the way, in your code nameCard is not defined at all.

Please check these code

could you check these codes?
I can't find the problem.
"If" has no action!
It should check username and password and age.
After that if all of details are true will answer true unless will answer false.But "If" don't answer.
import java.util.Scanner;
public class Class2 {
public static void main(String[] args) {
int age;
String password = "big.110#go";
String username = "big";
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Please enter your Usename: ");
username = keyboardInput.next();
System.out.print("Please enter your age: ");
age = keyboardInput.nextInt();
System.out.print("Please enter your password: ");
password = keyboardInput.next();
if(keyboardInput.next().equals(username)
&& keyboardInput.nextInt() >= 18
&& keyboardInput.equals(password)) {
System.out.print("Welcome");
} else {
System.out.print("Something is wrong!\n Try again");
}
}
}
You made a lot of mistake in your code.
import java.util.Scanner;
public class Class2 {
public static void main(String args[]) {
int age;
String password1 = "big.110#go";
String username1 = "big";
Scanner keyboardInput = new Scanner(System.in);
System.out.print("Please enter your Usename: ");
String username = keyboardInput.nextLine();
System.out.print("Please enter your password: ");
String password = keyboardInput.nextLine();
System.out.print("Please enter your age: ");
age = keyboardInput.nextInt();
if(username.equals(username1)
&& password.equals(password1)
&& age>=18 ) {
System.out.print("Welcome");
} else {
System.out.print("Something is wrong!\n Try again");
}
}
}

I keep encountering the error " Error: Syntax error, insert "}" to complete ClassBody"

I know there are other errors present but the main one is the bracket that is supposed to close my main method. It ask me to enter another bracket to close the class body. I have gone through many times, correctly indenting and entering in brackets to close loops and methods but it just doesn't want to work. Any ideas?
import java.util.Stack;
import java.util.Scanner;
public class RPNApp{
public static void main (String [] args)
{
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String [ ] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i <= userInput.length; i++) {
if (isNumber()) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
}
}
}
public static boolean isOperator (String userInput[i]) //userInput is the array.
{
for (int i = 0; i<userInput.length; i++) {
if (!(x.equals("*") || x.equals("+") || x.equals("-") || x.equals("/") || x.equals("%"))) {
return false;
}else {
return true;
}
}
}
public static boolean isNumber (String userInput[i])
{
for (int i = 0; i<x.length(); i++) {
char c = x.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
} return true;
}
}
I have made quite a few changes, I knew there were other errors present. But the error I encountered from not having a correct parameter in my method was the worry. You mentioned there was still something wrong, have I tended to the syntax error you noticed?
Updated code
import java.util.Stack;
import java.util.Scanner;
public class RPNApp{
public static void main (String [] args){
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String [ ] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i < userInput.length; i++) {
String current = userInput[i];
if (isNumber(current)) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
System.out.println(stack.toString());
}
}
}
public static boolean isOperator (String x) { //userInput is the array.
if (!(x.equals("*") || x.equals("+") || x.equals("-") || x.equals("/") || x.equals("%"))) {
return false;
}else {
return true;
}
}
public static boolean isNumber (String x) {
for (int i = 0; i<x.length(); i++) {
char c = x.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
} return true;
}
}
This piece of code certainly has more than just a few issues. But if you have written it entirely in your head without ever compiling it, it's actually pretty good! It shows that you think about the problem in a surprisingly correct way. I don't understand how one can get so many details wrong, but the overall structure right. And some of the syntax errors aren't really your fault: it's absolutely not obvious why it should be array.length but string.length() but at the same time arrayList.size(), it's completely inconsistent mess.
Here, I cleaned it up a bit:
import java.util.Stack;
import java.util.Scanner;
public class RPNApp {
public static void main(String[] args) {
/* Scanner object which takes user input and splits each element into an array of type String*/
Scanner scan = new Scanner(System. in );
System.out.println("Please enter numbers and operators for the Reverse Polish Notation calculator.");
String scanner = scan.nextLine();
String[] userInput = scanner.split(" ");
Stack<Long> stack = new Stack<Long>();
for (int i = 0; i <= userInput.length; i++) {
if (isNumber(userInput[i])) {
Long.parseLong(userInput[i]);
stack.push(Long.parseLong(userInput[i]));
}
}
}
public static boolean isOperator(String userInput) {
for (int i = 0; i < userInput.length(); i++) {
char x = userInput.charAt(i);
if (!(x == '*' || x == '+' || x == '-' || x == '/' || x == '%')) {
return false;
}
}
return true;
}
public static boolean isNumber(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c))) {
return false;
}
}
return true;
}
}
Few other points to notice:
Exists-loops: Check if true, return true in loop, return false in the end.
Forall-loops: Check if false, return false in loop, return true in the end.
Chars and Strings are not the same. Chars are enclosed in single quotes and compared by ==.
It's still wrong. Think harder why. And try not to post non-compilable stuff any more.
In your function parameters you can't have userInput[i] like that. Get rid of the [i] part and then fix the rest of the other errors.

Reading from a textfile and sorting the list afterwards

I have an assignment where I am required to read a file from a textfile and add the lines to a list, sort it by length and print it out. My problem is that Coolections.sort() sorts it both alphabetically and by length, I am required to only sort it by length, here is my code so far.
import java.util.*;
import java.io.*;
public class Question3
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(System.in);
String path = input.nextLine();
Scanner scanner = new Scanner(new File(path));
List<String> lines = new ArrayList<String>();
while(scanner.hasNext())
{
lines.add(scanner.next());
}
Collections.sort(lines);
System.out.println(lines);
}
}
Collections.sort(strings, new Comparator<String>() {
#Override
public int compare(String str1, String str2) {
if(str1.length() > str2.length())
return 1;
else if(str1.length() < str2.length())
return -1;
else
return 0;
}
});
This will sort the strings based on their length in ascending order, please clean up the above code as required.

Print Web Service Response

I am trying to call a webservice and print the some of the response.
When I run this code, I get XML response with ID, FIRSTNAME, LASTNAME, STREET, CITY. So for example how can I print out only CITY?
static int customerId = 123456;
public static void main(String[] args) throws Exception {
URL oracle = new URL(
"http://www.thomas-bayer.com/sqlrest/CUSTOMER/" + customerId);
BufferedReader in = new BufferedReader(new InputStreamReader(
oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
Thank you in advance.
This may be a tweak code but still this will do.
static int customerId = 123456;
static String str="";
public static void main(String[] args) throws Exception
{
URL oracle = new URL("http://www.thomas-bayer.com/sqlrest/CUSTOMER/" + customerId);
BufferedReader in = new BufferedReader(new InputStreamReader(
oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
//code change stats here
if(inputLine.contains("<CITY>")){
str=inputLine;
}
}
String city=str.replace("<CITY>","");
System.out.println(city.replace("</CITY>", ""));
//code change ends here
in.close();
}
This should be the best one :
Call this method in the while loop by passing the key and the string:
public static String getvalue(String xmlkey,String xmlstring) throws
ParserConfigurationException, SAXException, IOException{
System.out.println(xmlstring+"dff");
InputStream is = new ByteArrayInputStream(xmlstring.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = null;
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName(xmlkey);
if (nl != null) {
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
  String name = item.getNodeName();
  String value = item.getTextContent();
System.out.println(name+" "+value+" value and name");
}
}
return value;
} catch(Exception e) {
e.printStackTrace();
}
   
}