Could you please explain why this loop doesn't work in case if user types "yes" and why there are errors with variables initialisations.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner src;
String amount;
String counterparty;
String dt;
String ct;
System.out.println("Create new transaction:yes/no");
Scanner abc = new Scanner(System.in);
String g = abc.nextLine();
if (g=="yes") {
System.out.println("Amount of transaction:");
src = new Scanner(System.in);
amount = src.nextLine();
System.out.println("Counterparty:");
counterparty = src.nextLine();
System.out.println("Dt:");
dt = src.nextLine();
System.out.println("Ct:");
ct = src.nextLine();
}
else if (g=="no") {
amount="0";
}
System.out.println("Transaction:");
ArrayList <String> Provodka = new ArrayList();
Provodka.add(amount);
Provodka.add(counterparty);
Provodka.add(dt);
Provodka.add(ct);
for (int i = 0; i < Provodka.size(); i++) {
String value = Provodka.get(i);
System.out.println("Element: " + value);
}
}
}
Just initialize the local variables and use equals() method instead of "=="
public static void main(String args[]) {
Scanner src;
String amount = null;
String counterparty = null;
String dt = null;
String ct = null;
System.out.println("Create new transaction:yes/no");
Scanner abc = new Scanner(System.in);
String g = abc.nextLine();
if (g.equals("yes"))
{
System.out.println("Amount of transaction:");
src = new Scanner(System.in);
amount = src.nextLine();
System.out.println("Counterparty:");
counterparty = src.nextLine();
System.out.println("Dt:");
dt = src.nextLine();
System.out.println("Ct:");
ct = src.nextLine();
}
else if (g.equals("no")){
amount="0";
}
System.out.println("Transaction:");
ArrayList <String> Provodka = new ArrayList();
Provodka.add(amount);
Provodka.add(counterparty);
Provodka.add(dt);
Provodka.add(ct);
for (int i = 0; i < Provodka.size(); i++) {
String value = Provodka.get(i);
System.out.println("Element: " + value);
}
}
In your string comparison you are comparing strings with '==' .
Use equals() method to compare strings.
eg:-
if ("yes".equals(g)){
}
Firstly, there is a lot of unnecessary declaration of Scanner. Using one variable for scanner will work for all inputs. Secondly, declare your variables above the main method and make them static, here you will not always need to initialise them. Finally, use g.equalsIgnoreCase("yes") instead of g == "yes", this way if you type yes in CAPS or not it will still register. Try what was done below
public static String g;
public static String amount;
public static String counterparty;
public static String dt;
public static String ct;
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Create new transaction:yes/no");
g= s.nextLine();
if (g.equalsIgnoreCase("yes")) {
System.out.println("Amount of transaction: ");
amount = s.nextLine();
System.out.println("Counterparty: ");
counterparty = s.nextLine();
System.out.println("Dt: ");
dt = s.nextLine();
System.out.println("Ct: ");
ct = s.nextLine();
}
else if (g.equalsIgnoreCase("no")) {
amount = "0";
}
System.out.println("Transaction:");
ArrayList <String> Provodka = new ArrayList();
Provodka.add(amount);
Provodka.add(counterparty);
Provodka.add(dt);
Provodka.add(ct);
for (int i = 0; i < Provodka.size(); i++) {
String value = Provodka.get(i);
System.out.println("Element: " + value);
}
}
}
Related
I've created a class Scoreboard that will store entries of the name of a player, their power, their score, and their rank amongst other players. I want to use Collections.binarySearch() to retrieve the correct object of the name the user enters. However, it only gives back negative indexes. Any help is appreciated.
My comparator object:
import java.util.Comparator;
public class SortByName implements Comparator<Scoreboard> {
#Override
public int compare(Scoreboard s1, Scoreboard s2) {
return s1.getName().compareTo(s2.getName());
}
}
My main class:
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Main {
public static void main (String args[]) throws IOException {
String get = "";
Scanner in = new Scanner(System.in);
Scanner inFile = new Scanner(new File("input.txt"));
// Temporarily saves the attributes of each Scoreboard object being created
int score;
int entryCount = 0;
String name = "";
String power;
ArrayList<Scoreboard> scoreboard = new ArrayList<>();
String line;
while (inFile.hasNextLine()) {
line = inFile.nextLine();
if (line == "") {
continue;
}
ArrayList<String> lineArray = new ArrayList<>();
for (int i = 0; i < line.split(" ").length; i++) {
lineArray.add(line.split(" ")[i]);
}
if (lineArray.size() < 3) {
continue;
}
try {
score = Integer.parseInt(lineArray.get(0));
lineArray.remove(0);
} catch (NumberFormatException e) {
continue;
}
entryCount++;
power = lineArray.get(lineArray.size() - 1);
lineArray.remove(lineArray.size() - 1);
for (int i = 0; i < lineArray.size(); i++) {
name += lineArray.get(i) + " ";
}
scoreboard.add(new Scoreboard(name, power, score, entryCount, entryCount));
name = "";
}
String input;
do {
System.out.print("Search name: ");
input = in.nextLine();
if ((input.equalsIgnoreCase("exit"))) break;
System.out.println("");
Collections.sort(scoreboard);
for (Scoreboard element:scoreboard) {
System.out.print(element);
}
System.out.println(input);
System.out.println(Collections.binarySearch(scoreboard, new Scoreboard(input, null, 0, 0, scoreboard.get(0).getRankOutOf()), new SortByName()));
} while (true);
}
}
import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
reverse(s1);
System.out.println(reverse(s1));
}
public static int reverse(int strNum) {
String s1 = Integer.toString(strNum);
for(int i=s1.length()-1;i>=0;i--){
System.out.print(s1.charAt(i));
}
return 0;
}
}
Pretty straight forward - I want to reverse my input of numbers, but I am unable to.
There are errors at 'reverse(s1);' and 'System.out.println(reverse(s1));' , as s1 is not recognized. I cannot figure out the cause.
Your code will not compile as is. s1 is not in main method and reverse method is accepting an int not String.
Also, if you need to return an int from your method why not the reversed int which is the answer.
Few edits to your code which will solve your issue.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
System.out.println(reverse(num));
}
public static int reverse(int num) {
String strNum = String.valueOf(num);
StringBuffer sb = new StringBuffer();
for(int i=strNum.length()-1;i>=0;i--)
sb.append(strNum.charAt(i));
return Integer.parseInt(sb.toString());
}
import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
reverse(strNum);
}
public static int reverse(String strNum) {
String s1 =strNum;
for(int i=s1.length()-1;i>=0;i--){
System.out.print(s1.charAt(i));
}
return 0;
}
}
You don't have any variable s1
you assigned value of string number to 'strNum', So use it instead
Also you have to use string as argument type in definition of reverse()
import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
reverse(s1);
System.out.println(reverse(s1));
}
public static int reverse(String strNum) {
for(int i=strNum.length()-1;i>=0;i--){
System.out.print(strNum.charAt(i));
}
return 0;
}
}
StringBuilder sb = new StringBuilder("your string");
String result = sb.reverse().toString();
// ===============try the below code===============================
public static void main(String sr[])
{
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
String inputString = String.valueOf(num);
StringBuilder builder = new StringBuilder(inputString);
System.out.println(builder.reverse());
}
You can easily use stack , below is a simple implementation of reversing a string by using stack. You can easily change the code for Integer, The complexity is O(n) which is good i think.
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
String retVal = "";
Scanner s = new Scanner(System.in);
try {
String nextStr = String.valueOf(s.nextInt());
for (int i = 0; i < nextStr.length(); i++) {
stack.push(String.valueOf(nextStr.charAt(i)));
}
for (int i = 0; i < nextStr.length(); i++) {
retVal+=stack.pop();
}
System.out.println(retVal);
} finally {
s.close();
}
}
import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
System.out.println(new StringBuilder(String.valueOf(num)).reverse().toString());
}
}
we can use stringBuffer or StringBuilder for reversing
I'm bothering with such problem for long hours:
Task is " blah blah.. You will then be given an unknown number of names to query your phone book for.. "
And Like I said int title I'm using this condition "hasNext". How I can break this loop without clear knowledge of ending input, what will be write in console and amout of input? I was thinking that do while loop will help me, but still without expected result :(.
Thanks for any answers and sorry if it's so obvious to answear-I was looking for similar questions/answears, but none of it worked :(
EDIT( and complete task is here: https://www.hackerrank.com/challenges/30-dictionaries-and-maps):
public class Test {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int k = 0; k < a; k++) {
String name = sc.next();
int numer = sc.nextInt();
map.put(name, numer);
}
while(sc.hasNext()){
String name=sc.next();
sc.nextLine();
list.add(name);
}
sc.close();
for (String k : list) {
if (map.containsKey(k)) {
System.out.println(k + "=" + map.get(k));
} else {
System.out.println("Not found");
}
}
}
}
A possible solution for your problem:
public static void main(String[] args) throws IOException
{
HashMap<String, Integer> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int k = 0; k < a; k++) {
String name = sc.next();
int numer = sc.nextInt();
map.put(name, numer);
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String name;
while ((name = in.readLine()) != null && name.length() != 0)
{
list.add(name);
}
for (int i = 0; i < list.size(); i++)
{
if (map.containsKey(list.get(i)))
{
System.out.println(list.get(i) + "=" + map.get(list.get(i)));
} else
{
System.out.println("Not found");
}
}
sc.close();
}
I think you might be looking for break.
while(scanner.hasNext()){
String next = scanner.nextLine();
if(next.equals("quit")){
//you will exit the loop here
break;
}
System.out.println(next);
//more code here
}
It is already solved, but maybe it would help someone in future :D
public class Test {
public static void main(String[] args) {
HashMap<String,Integer> mapa = new HashMap<>();
ArrayList<String> lista = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
boolean condition = true;
for(int k = 0; k < a; k++) {
String imie = sc.next();
int numer = sc.nextInt();
mapa.put(imie, numer);
}
while(condition == true) {
try {
String line;
while(!(line = sc.nextLine()).isEmpty()) {
lista.add(line);
}
}
catch(NoSuchElementException exception) {
condition=false;
}
}
sc.close();
for(String k: lista) {
if(mapa.containsKey(k))
System.out.println(k + "=" + mapa.get(k));
else
System.out.println("Not found");
}
}
}
I'm working on a project where I have a text file with the first line being the size of the array I'll need and then subsequent lines have course information in the following order: dept, num, title. (ex. CSC 101 Basic Computing) My code complies but when it runs the first index in the array becomes the default(i.e. nothing) and therefore the last line in the text file doesn't get stored or printed. I'm wondering how I can fix this error.
import java.util.Scanner;
import java.io.*;
public class Organizer {
public static void main(String[] args) {
Scanner fileScanner = null;
String file;
File f = null;
//Create a Do While loop in order to prompt the user for a input file
//and then continue prompting if the file entered does not exist.
do {
try {
System.out.print("What is the name of the input file? ");
Scanner inputReader = new Scanner(System.in);
file = inputReader.nextLine();
f = new File(file);
fileScanner = new Scanner(new File(file));
//Catch the exception and tell the user to try again
} catch (FileNotFoundException e) {
System.out.println("Error scanning that file, please try again.");
}
} while (!f.exists());
//Testing the Make Array Method
//System.out.print(makeArray(fileScanner));
//Testing the print Array Method
printArray(makeArray(fileScanner));
}
public static Course[] makeArray(Scanner s) {
int arraySize = s.nextInt();
String title = "";
String dept = "";
int num = 0;
Course[] a = new Course[arraySize];
for (int i = 0; i < a.length; i++) {
a[i] = new Course(dept, num, title);
String oneLine = s.nextLine();
Scanner lineReader = new Scanner(oneLine);
while (lineReader.hasNext()) {
dept = lineReader.next();
a[i].setDept(dept);
num = lineReader.nextInt();
a[i].setNum(num);
while (lineReader.hasNext()) {
title = title + lineReader.next() + " ";
}
a[i].setTitle(title);
}
title = " ";
}
return a;
}
public static void printArray(Course[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].toString());
}
}
}
Here is my other class.
public static class Course {
//INSTANCE VARIABLES
private String dept = "";
private int num = 0;
private String title = "";
//CONSTRUCTORS
public Course(String dept, int num) {
this.dept = dept;
this.num = num;
}
public Course(String dept, int num, String title) {
this.dept = dept;
this.num = num;
this.title = title;
}
public Course() {
this.dept = "AAA";
this.num = 100;
this.title = "A course";
}
//SETTER AND GETTER METHODS
public void setDept(String dept) {
this.dept = dept;
}
public void setNum(int num) {
this.num = num;
}
public void setTitle(String title) {
this.title = title;
}
public String getDept() {
return this.dept;
}
public int getNum() {
return this.num;
}
public String getTitle() {
return this.title;
}
//TOSTRING METHOD
public String toString() {
return dept + " " + num + ": " + title;
}
}
Don't forget where your cursor in your Scanner is at each moment.
s.nextLine() will read the whole line and then the cursor will jump to the next line, while s.nextInt() will read one int from your line and then stay there. It won't check if this has been the last input for that line.
Just fix your code to:
int arraySize = s.nextInt();
s.nextLine();
and your code should run just fine!
(also consider changing a[i].setTitle(title); to a[i].setTitle(title.trim());, since you will always be left with a white space at the end of your title..)
nextInt method does not consume the new line character. Here is a solution that works:
public static Course[] makeArray(Scanner s){
int arraySize = s.nextInt();
String title = "";
String dept = "";
int num = 0;
Course[] a = new Course[arraySize];
s.nextLine();
for (int i = 0; i < a.length; i++){
a[i] = new Course(dept, num, title);
String oneLine = s.nextLine();
Scanner lineReader = new Scanner(oneLine);
while (lineReader.hasNext()){
dept = lineReader.next();
a[i].setDept(dept);
num = lineReader.nextInt();
a[i].setNum(num);
while (lineReader.hasNext()){
title = title + lineReader.next() + " ";
}
a[i].setTitle(title);
}
title = " ";
}
return a;
}
Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
// Will recognize a space in words
if(Character.isWhitespace(welcome.charAt(i))) {
Character a = welcome.charAt(i);
}
}
What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string.
Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
Here is the way you can reversed the word in entered string:
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if(!s.trim().contains(' ')) {
return s;
}
else {
StringBuilder reversedString = new StringBuilder();
String[] sa = s.trim().split(' ');
for(int i = sa.length() - 1; i >= 0: i - 1 ) {
reversedString.append(sa[i]);
reversedString.append(' ');
}
return reversedString.toString().trim();
}
Hope this helps.
If you wanted to reduce the number of line of code, I think you can look into my code :
package com.sujit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StatementReverse {
public static void main(String[] args) throws IOException {
String str;
String arr[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string:");
str = br.readLine();
arr = str.split("\\s+");
for (int i = arr.length - 1;; i--) {
if (i >= 0) {
System.out.print(arr[i] + " ");
} else {
break;
}
}
}
}
public class StringReverse {
public static void main(String[] args) {
String str="This is anil thakur";
String[] arr=str.split(" ");
StringBuilder builder=new StringBuilder("");
for(int i=arr.length-1; i>=0;i--){
builder.append(arr[i]+" ");
}
System.out.println(builder.toString());
}
}
Output: thakur anil is This
public class ReverseWordTest {
public static String charRev(String str) {
String revString = "";
String[] wordSplit = str.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
String revWord = "";
String s2 = wordSplit[i];
for (int j = s2.length() - 1; j >= 0; j--) {
revWord = revWord + s2.charAt(j);
}
revString = revString + revWord + " ";
}
return revString;
}
public static void main(String[] args) {
System.out.println("Enter Your String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(charRev(str));
}
public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
if(count==0||count==x.length) //that's for two edges.
one=s+one;
else
one=s+" "+one;
count++;
}
System.out.println(one); //reverse.
}